package tt.dz.service.imp.sys;

import java.math.BigDecimal;
import java.sql.Time;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;

import redis.clients.jedis.Jedis;
import tt.dz.dao.base.OmsCommonDao;
import tt.dz.dao.ext.charger.OmsChargerChargeBillRecordDao;
import tt.dz.dao.ext.charger.OmsChargerDao;
import tt.dz.dao.ext.charger.OmsChargerErrorRecordDao;
import tt.dz.dao.ext.charger.OmsChargerOfflineWhitelistDao;
import tt.dz.dao.ext.charger.OmsChargerSoftwareRefreshDao;
import tt.dz.dao.ext.charger.OmsChargerStateAlternateDao;
import tt.dz.dao.ext.charger.OmsChargerStateDirectDao;
import tt.dz.dao.ext.common.OmsSplitratioSchemeDao;
import tt.dz.dao.ext.station.OmsStationDao;
import tt.dz.entity.base.JsonCommon;
import tt.dz.entity.base.OmsServiceSplitratio;
import tt.dz.entity.base.OmsSplitratioScheme;
//import tt.dz.tcp.rpc.ms.client.SystemMasterServerRpcClientService;
import tt.dz.entity.charger.OmsCharger;
import tt.dz.entity.charger.OmsChargerChargeBillRecord;
import tt.dz.entity.charger.OmsChargerErrorRecord;
import tt.dz.entity.charger.OmsChargerOfflineWhitelist;
import tt.dz.entity.charger.OmsChargerRate;
import tt.dz.entity.charger.OmsChargerSoftwareRefresh;
import tt.dz.entity.charger.OmsChargerStateAlternate;
import tt.dz.entity.charger.OmsChargerStateDirect;
import tt.dz.entity.exception.BizException;
import tt.dz.entity.exception.OmsDaoException;
import tt.dz.entity.station.OmsStation;
import tt.dz.service.charger.ChargerRateService;
import tt.dz.service.imp.middleware.MessageAnalysisHelper;
import tt.dz.service.imp.middleware.MessageWrapper;
import tt.dz.service.imp.middleware.vo.ChargerSendingMsgHeader;
import tt.dz.service.imp.middleware.vo.statechange.ChargingStateBody;
import tt.dz.service.imp.middleware.vo.statechange.ChargingStoppedStateBody;
import tt.dz.service.imp.middleware.vo.statechange.DownStateBody;
import tt.dz.service.imp.middleware.vo.statechange.StateChangeBody;
import tt.dz.service.imp.middleware.vo.statechange.TapCardStateBody;
import tt.dz.service.middleware.EncapsulationService;
import tt.dz.service.sys.ChargerUploadService;
import tt.dz.tcp.rpc.as.SystemAppServerRpcClient;
import tt.dz.tcp.rpc.ms.SystemMasterServerRpcClient;
import tt.dz.tcp.rpc.ms.client.entity.MasterQueryIdentityCardVO;
import tt.dz.tcp.rpc.ms.client.entity.MasterQueryOfflineCardVO;
import tt.dz.tcp.rpc.os.OrderRpcClient;
import tt.dz.util.CardUtils;
import tt.dz.util.DateUtils;
import tt.dz.util.OmsConstant;
import tt.dz.util.OmsConstant.ErrorCodeEnum;
import tt.dz.util.OmsConstant.MsgFaultCodeEnum;
import tt.dz.util.OrderConstant.BizSystemCode;
import tt.dz.util.OrderConstant.CardType;
import tt.dz.util.OrderConstant.OrderServiceEnum;
import tt.dz.util.RedisClient;
import tt.dz.util.StringUtil;
import tt.dz.util.serialGenerater;
import tt.dz.vo.os.OrderBaseData;
import tt.dz.vo.os.OrderBaseData.DivideInfo;

@Service @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class ChargerUploadServiceImpl  implements ChargerUploadService{
	private Log log = LogFactory.getLog(ChargerUploadServiceImpl.class);

	@Resource
	OmsChargerDao omsChargerDao;
	@Resource
	OmsStationDao omsStationDao;
	@Resource
	OmsChargerStateDirectDao stateDirectDao;
	@Resource
	OmsChargerStateAlternateDao stateAlternateDao;
	@Resource
	OmsChargerSoftwareRefreshDao omsChargerSoftwareRefreshDao;
	@Resource
	OmsChargerChargeBillRecordDao omsChargerChargeBillRecordDao;
	@Resource
	OmsChargerErrorRecordDao omsChargerErrorRecordDao;
	@Resource
	OmsChargerOfflineWhitelistDao omsChargerOfflineWhitelistDao;
	@Autowired
	@Qualifier("base")
	private OmsCommonDao<OmsServiceSplitratio> serviceSplitratioDaoImpl;
	@Resource
	OmsSplitratioSchemeDao omsSplitratioSchemeDao;
	@Resource
	OrderRpcClient orderRpcClient;
	@Resource
	ChargerRateService chargerRateService;
	@Resource
	SystemMasterServerRpcClient mainServerClient;
	@Resource
	SystemAppServerRpcClient systemAppServerRpcClient;
	@Resource(name = "ev3c2EncapsulationServiceImpl")
	EncapsulationService ev3c2EncapsulationService;
	@Resource
	MessageWrapper messageWrapper;

	@SuppressWarnings("rawtypes")
	JsonCommon json = new JsonCommon();
	
	@SuppressWarnings("rawtypes")
	@Override
	public JsonCommon uploadChange(String chargerId, String status_type, String status_value) {
		JsonCommon json = new JsonCommon();
		OmsCharger charger_query = new OmsCharger();
		charger_query.setCharger_id(chargerId);
		List<OmsCharger> chargerList = omsChargerDao.findExample(charger_query, null, null, null, null);
		if(chargerList==null||chargerList.get(0).getCharger_type()==null){
			json.setCode("10301201");
			json.setMsg("charger not found");
			return json;
		}
		status_value = status_value.substring(5, 6);
		int chargerType = chargerList.get(0).getCharger_type();
		switch (chargerType) {//1--直流  2--交流  3--混合
		case 1:
			OmsChargerStateDirect directState_query =  new OmsChargerStateDirect();
			directState_query.setCharger_id(chargerId);
			List<OmsChargerStateDirect> directStateList =  stateDirectDao.findExample(directState_query,null,null,null, null);
			for(OmsChargerStateDirect direct : directStateList){
				switch(status_type){
				case "01"://01：充电口使用状态
					status_value = status_value.substring(5, 6);
					switch(status_value){//  数据库中   0: 空闲;1: 预约;2 充电; 3 故障
					case "00"://00：空闲
						direct.setCharge_status(0);
						break;
					case "01"://01：充电中
						direct.setCharge_status(2);
						break;
					case "02"://02：预约中
						direct.setCharge_status(1);
						break;
					default:
						break;
					}
					stateDirectDao.updateObject(direct);
					break;
				case "02"://02：故障状态
					direct.setCharge_status(3);
					json.setCode("103013 + 故障码："+status_value);
					MsgFaultCodeEnum msgFaultCodeEnum = MsgFaultCodeEnum.getMsgFaultCodeEnum(status_value);
					switch(msgFaultCodeEnum){
					case Normal://正常	
						json.setMsg("正常");
						break;
					case OtherFault://其他故障
						json.setMsg("其他故障");
						break;
					case EmergencyStop://急停故障
						json.setMsg("急停故障");
						break;
					case Ammeter://电表故障
						json.setMsg("电表故障");
						break;
					case Switches://接触器故障
						json.setMsg("接触器故障");
						break;
					case cardReader://读卡器故障
						json.setMsg("读卡器故障");
						break;
					case OverTemperature://内部过温故障
						json.setMsg("内部过温故障");
						break;
					case Connector://连接器故障
						json.setMsg("连接器故障");
						break;
					case Isolation://绝缘故障
						json.setMsg("充电枪未插好");
						break;
					case OutputCurrentAbnormal://输出电流异常
						json.setMsg("输出电流异常");
						break;
					case OutputVoltageAbnormal://输出电压异常
						json.setMsg("输出电压异常");
						break;
					case ChargerModule://充电机模块故障
						json.setMsg("充电机模块故障");
						break;
					case ChargerCommunication://充电机通信故障
						json.setMsg("充电机通信故障");
						break;
					case BMSProhibitCharge://BMS禁止充电
						json.setMsg("BMS禁止充电");
						break;
					case InputVoltageAbnormal://输入电压异常
						json.setMsg("输入电压异常");
						break;
					default://
						json.setMsg("未知故障");
						break;
					}
					stateDirectDao.updateObject(direct);
					break;
				case "03"://03：停车位状态
					break;
				default:
					break;
				}
			}
			break;
		case 2:
//			OmsChargerStateAlternate alternateState_query =  new OmsChargerStateAlternate();
//			alternateState_query.setCharger_id(chargerId);
//			alternateState = stateAlternateDao.findOneExample(alternateState_query,null,null);
//			alternateState.setCharge_status(2);
//			stateAlternateDao.updateObject(alternateState);
//			if((alternateState.getOnline_status()==1)&&(alternateState.getCharge_status()==1)&&(alternateState.getCable_status()==1)){
//				isBespeak = 1;
//			}
			OmsChargerStateAlternate alternateState_query =  new OmsChargerStateAlternate();
			alternateState_query.setCharger_id(chargerId);
			List<OmsChargerStateAlternate> alternateStateList =  stateAlternateDao.findExample(alternateState_query,null,null,null, null);
			for(OmsChargerStateAlternate alternate : alternateStateList){
				switch(status_type){
				case "01"://01：充电口使用状态
					status_value = status_value.substring(5, 6);
					switch(status_value){//  数据库中   0: 空闲;1: 预约;2 充电; 3 故障
					case "00"://00：空闲
						alternate.setCharge_status(0);
						break;
					case "01"://01：充电中
						alternate.setCharge_status(2);
						break;
					case "02"://02：预约中
						alternate.setCharge_status(1);
						break;
					default:
						break;
					}
					stateDirectDao.updateObject(alternate);
					break;
				case "02"://02：故障状态
					alternate.setCharge_status(3);
					json.setCode("103013 + 故障码："+status_value);
					MsgFaultCodeEnum msgFaultCodeEnum = MsgFaultCodeEnum.getMsgFaultCodeEnum(status_value);
					switch(msgFaultCodeEnum){
					case Normal://正常	
						json.setMsg("正常");
						break;
					case OtherFault://其他故障
						json.setMsg("其他故障");
						break;
					case EmergencyStop://急停故障
						json.setMsg("急停故障");
						break;
					case Ammeter://电表故障
						json.setMsg("电表故障");
						break;
					case Switches://接触器故障
						json.setMsg("接触器故障");
						break;
					case cardReader://读卡器故障
						json.setMsg("读卡器故障");
						break;
					case OverTemperature://内部过温故障
						json.setMsg("内部过温故障");
						break;
					case Connector://连接器故障
						json.setMsg("连接器故障");
						break;
					case Isolation://绝缘故障
						json.setMsg("充电枪未插好");
						break;
					case OutputCurrentAbnormal://输出电流异常
						json.setMsg("输出电流异常");
						break;
					case OutputVoltageAbnormal://输出电压异常
						json.setMsg("输出电压异常");
						break;
					case ChargerModule://充电机模块故障
						json.setMsg("充电机模块故障");
						break;
					case ChargerCommunication://充电机通信故障
						json.setMsg("充电机通信故障");
						break;
					case BMSProhibitCharge://BMS禁止充电
						json.setMsg("BMS禁止充电");
						break;
					case InputVoltageAbnormal://输入电压异常
						json.setMsg("输入电压异常");
						break;
					default://
						json.setMsg("未知故障");
						break;
					}
					stateAlternateDao.updateObject(alternate);
					break;
				case "03"://03：停车位状态
					break;
				default:
					break;
				}
			}
			break;	
		default:	
			break;	
		}
		return json;
	}
	@SuppressWarnings("rawtypes")
	@Override
	public JsonCommon uploadFirmwareStatus(Map<String, String> map) {
		JsonCommon json = new JsonCommon();
		String status = map.get("status");
		String chargerId = map.get("chargerId");
		//查询oms_charger_software_refresh[桩固件更新记录]中最近一次时间的记录
		OmsChargerSoftwareRefresh omsChargerSoftwareRefresh_query = new OmsChargerSoftwareRefresh();
		omsChargerSoftwareRefresh_query.setCharger_id(chargerId);
		OmsChargerSoftwareRefresh omsChargerSoftwareRefresh = omsChargerSoftwareRefreshDao.findOneExample(omsChargerSoftwareRefresh_query, "update_time ", "desc");
		/*
		 * 00：升级完成（初始状态值）
			01：下载中
			02：下载完成
			03：开始安装
			FF：升级失败
		 * */
		String additional_data_map ="";
		additional_data_map = map.get("additional_data");
		String additional_data ="";
		if(status.equals("FF")){
			switch(additional_data_map.substring(0, 2)){
			case "01":
				additional_data ="下载服务器连接失败";
				break;
			case "02":
				additional_data ="下载服务器拒绝下载";
				break;
			case "03":
				additional_data ="下载中断且无法继续";
				break;
			case "04":
				additional_data ="下载完成，MD5校验失败";
				break;
			case "FF":
				additional_data ="固件升级失败原因：其他原因";
				break;
			default:
				break;
			}
		}
		//如果没有记录，就insert，反之则update
		if(omsChargerSoftwareRefresh!=null){
			omsChargerSoftwareRefresh.setUpdate_status(status);
			if(status.equals("FF")){
				omsChargerSoftwareRefresh.setAdditional_data(additional_data);
			}else if(additional_data_map!=null){
				omsChargerSoftwareRefresh.setAdditional_data(additional_data_map);
			}
			omsChargerSoftwareRefreshDao.updateObject(omsChargerSoftwareRefresh);
		}else{
			OmsChargerSoftwareRefresh omsChargerSoftwareRefresh_insert = new OmsChargerSoftwareRefresh();
			if(status.equals("FF")){
				omsChargerSoftwareRefresh_insert.setAdditional_data(additional_data);
			}else if(additional_data_map!=null){
				omsChargerSoftwareRefresh_insert.setAdditional_data(additional_data_map);
			}
			omsChargerSoftwareRefresh_insert.setCharger_id(chargerId);
			omsChargerSoftwareRefresh_insert.setUpdate_status(status);
			//用桩上传的时间
			String serialNumber = map.get("serialNumber");
			String ymd = serialNumber.substring(0, 8);
			SimpleDateFormat sdf =   new SimpleDateFormat("yyyyMMdd");
			Date date;
			try {
				date = sdf.parse(ymd);
				omsChargerSoftwareRefresh_insert.setUpdate_time(date);
				omsChargerSoftwareRefresh_insert.setValid_flag(1);
				omsChargerSoftwareRefresh_insert.setCreate_time(date);
				omsChargerSoftwareRefreshDao.save(omsChargerSoftwareRefresh_insert);
			} catch (ParseException e) {
				json.setCode(ErrorCodeEnum.ParamValueError.value());
				json.setMsg("chargerId:"+chargerId+" status:"+status);
				e.printStackTrace();
				return json;
			}
		}
		json.setCode("200");
		json.setMsg("chargerId:"+chargerId+" status:"+status);
		return json;
	}
	@SuppressWarnings("rawtypes")
	@Override
	public JsonCommon uploadBill(Map<String, String> map) throws Exception
	{
		JsonCommon json = new JsonCommon();
		String protocol_version = map.get("protocol_version");
		switch(protocol_version){
		case "0101":
			json = uploadBill0101(map);
			break;
		case "0102":
			json = uploadBill0101(map);
			break;
		case "0103":
			json = uploadBill0103(map);
			break;
		default:
			break;
		}
		return json;
	
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon uploadBill0101(Map<String, String> map) throws Exception
	{
		JsonCommon json = new JsonCommon();
		String data = map.get("data");
		String userCard =data.substring(78, 98);
		// 如果是线下充值卡，就 1 数据库做记录，2  不传单价给订单服务器，调用订单接口 3 返回json
		if(userCard.startsWith("18806")){
			map.put("cardType", CardType.OFFLINE_CARD.value());
//			json = uploadBill18806_0101(map);
			json = commonUploadBill(map);
		}
		// 如果是线下卡（身份认证卡） ,则1 先查询数据库：  如果桩允许生成费用，则 2 数据库做记录；查询相关费率传总价给订单服务器，调用订单接口 3 返回json； 
		//如果桩不允许生成费用，则 查询单价 ，2 直接传总价给订单服务器，调用订单接口 ；数据库做记录3 返回json
		else if(userCard.startsWith("18805")){
			map.put("cardType", CardType.IDENTITY_CARD.value());
			json = commonUploadBill(map);
		}
		// 如果是线上卡app用户，,则1 先查询数据库：  如果桩允许生成费用，则 2 数据库做记录；查询相关费率传总价给订单服务器，调用订单接口 3 返回json； 
		//如果桩不允许生成费用，则 查询单价 ，2 直接传总价给订单服务器，调用订单接口 ；数据库做记录3 返回json
		else if(userCard.startsWith("18808")&&!userCard.substring(0, 9).equals("188089999")){
			map.put("cardType", CardType.ONLINE_CARD.value());
			json = uploadBill188089999_0101(map);
		}
		// 如果是线上卡企业用户，,则1 先查询数据库：  如果桩允许生成费用，则 2 数据库做记录；查询相关费率传总价给订单服务器，调用订单接口 3 返回json； 
		//如果桩不允许生成费用，则 查询单价 ，2 直接传总价给订单服务器，调用订单接口 ；数据库做记录3 返回json
		else if(userCard.startsWith("18808")){
			map.put("cardType", CardType.ONLINE_CARD.value());
			json = uploadBill18808_0101(map);
		}
		return json;
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon uploadBill18806_0101(Map<String, String> map) throws ParseException, OmsDaoException {

		//如果是线下充值卡，就 1 数据库做记录，2  不传单价给订单服务器，调用订单接口 3 返回json
		String data,chargerId,responseMsgHeader,requestURL; 
		JsonCommon json = new JsonCommon();
		data = map.get("data");
		chargerId = map.get("chargerId");
		OmsCharger omsCharger_query = new OmsCharger();
		OmsCharger omsCharger =omsChargerDao.findOneExample(omsCharger_query, null, null);
		if(omsCharger==null){
			json.setCode("10301201");
			json.setMsg("charge not found!");
			return json;
		}
		OmsStation omsStaionQuery = new OmsStation(omsCharger.getStation_id());
		OmsStation omsStation = omsStationDao.findRecordByPK(omsStaionQuery);
		
		String start_time =data.substring(50, 64);
		Date start_time_date =StringUtil.StrToDate(start_time);
//		start_time =  StringUtil.time14format(start_time);
//		long start_time_long = new java.text.SimpleDateFormat ("yyyy-MM-dd HH:mm:ss").parse(start_time).getTime();
		String end_time =data.substring(64, 78);
//		Date end_time_date =  StringUtil.time14format(end_time);
		Date end_time_date =StringUtil.StrToDate(end_time);
//		long end_time_long = new java.text.SimpleDateFormat ("yyyy-MM-dd HH:mm:ss").parse(end_time).getTime();
//		long charge_time = end_time_long - start_time_long;
		String userCard =data.substring(78, 98);
		float start_em = StringUtil.float16to10ByParamDesc(data.substring(98,106), 100); //*充电前电表读数 BIN码 4 系数为0.01 低字节在前，高字节在后，实际值X100上送
		float end_em = StringUtil.float16to10ByParamDesc(data.substring(106,114), 100); //*充电后电表读数 BIN码 4 系数为0.01 低字节在前，高字节在后，实际值X100上送
		float this_reading = StringUtil.float16to10ByParamDesc(data.substring(114,122), 100);//*本次充电电量  与上类似
		float this_amount_before = StringUtil.float16to10ByParamDesc(data.substring(122,130), 100);//*本次充电金额  与上类似
		float offline_balance_start = StringUtil.float16to10ByParamDesc(data.substring(130,138), 100);//充电前卡余额  与上类似
		float offline_balance_end = StringUtil.float16to10ByParamDesc(data.substring(138,146), 100);//充电后卡余额  与上类似
		float char_bill = StringUtil.float16to10ByParamDesc(data.substring(146,150), 100);//服务费金额  2   与上类似
		String offline_is_pay =data.substring(150, 152);//是否线下支付
		int offline_is_pay_int = Integer.valueOf(offline_is_pay,2);
//		String charge_end_reason =data.substring(152, 154);//充电结束原因
//		0x01: 后台远程控制正常结束
//		0x02: 本地刷卡控制正常结束
//		0x03: 满足预设停止条件正常结束
//		0x04：电池满电正常结束
//		String charge_start_mode = data.substring(154, 156);//充电启动方式 0x00：后台远程启动 0x01: 本地刷卡远程验证启动  0x02：本地刷卡白名单验证启动
//		String control_type = data.substring(156, 158);//控制类型  参考控制类型表对应数据，如0x04为自动充满方式。
//		String open_restricted_data = data.substring(158, 166);//开启限制数据  自动充满停机方式下无意义。低字节在前，高字节在后。电量控制,单位为“度”，精确到0.01,传输数据放大100倍；时间控制，单位为“秒“，精确到1,；金额控制，单位为“元”，精确到0.01，传输数据放大100倍。
//		String vehicle_identification_code = data.substring(166, 200);//车辆识别码
		OmsChargerChargeBillRecord  omsChargerChargeBillRecord_query  = new OmsChargerChargeBillRecord(); 
		omsChargerChargeBillRecord_query.setCharger_id(chargerId);
		omsChargerChargeBillRecord_query.setUser_pay_card(userCard);
		
		omsChargerChargeBillRecord_query.setStatus(4); // 0:开启充电(已下发指令未回复) 1:充电中(已确认桩回复)  2:电充满未结束(如未拔枪则是此状态)  3:关闭充电(已下发指令)  4:充电结束(桩回复充电结束)  5:已生成账单  6:已结算  7:已退款  8:充电失败
		OmsChargerChargeBillRecord  omsChargerChargeBillRecord = omsChargerChargeBillRecordDao.findOneExample(omsChargerChargeBillRecord_query, "create_time", "desc");
		if(omsChargerChargeBillRecord==null){
			json.setCode("10301201");
			json.setMsg("charge bill record not found!");
			return json;
		}
		//查询卡号是不是在白名单里面。
		OmsChargerOfflineWhitelist whitelist_query = new OmsChargerOfflineWhitelist();
		whitelist_query.setCharger_id(chargerId);
		whitelist_query.setUser_pay_card(userCard);
		OmsChargerOfflineWhitelist whitelist = omsChargerOfflineWhitelistDao.findOneExample(whitelist_query, null, null);
		if(whitelist!=null){
			char_bill = 0;
			this_amount_before = 0;
		}
		Date now = new Date();
		omsChargerChargeBillRecord.setEnd_time(end_time_date);
		omsChargerChargeBillRecord.setStart_time(start_time_date);
		
		long charge_time = now.getTime() - omsChargerChargeBillRecord.getStart_time().getTime();
		omsChargerChargeBillRecord.setStart_em(String.valueOf(start_em));
		omsChargerChargeBillRecord.setEnd_em(String.valueOf(end_em));
		omsChargerChargeBillRecord.setThis_reading(String.valueOf(this_reading));
		omsChargerChargeBillRecord.setThis_amount_before(this_amount_before);
		omsChargerChargeBillRecord.setThis_amount(this_amount_before);
		omsChargerChargeBillRecord.setChar_bill(char_bill);
		omsChargerChargeBillRecord.setOffline_balance_start(String.valueOf(offline_balance_start));
		omsChargerChargeBillRecord.setOffline_balance_end(String.valueOf(offline_balance_end));
		omsChargerChargeBillRecord.setStatus(5);
		omsChargerChargeBillRecord.setValid_flag(1);
//		omsChargerChargeBillRecord.setCharge_start_mode(charge_start_mode);
		omsChargerChargeBillRecord.setChar_bill(char_bill);
//		omsChargerChargeBillRecord.setCharge_end_reason(charge_end_reason);
//		omsChargerChargeBillRecord.setControl_type(control_type);
//		omsChargerChargeBillRecord.setOpen_restricted_data(open_restricted_data);
//		omsChargerChargeBillRecord.setVIN(vehicle_identification_code);
		omsChargerChargeBillRecord.setUser_pay_card(userCard);
		// 线上卡是18808开头  线下卡是18806开头
		if (offline_is_pay_int == 1){
			omsChargerChargeBillRecord.setOffline_is_pay(1);
		} else {
			omsChargerChargeBillRecord.setOffline_is_pay(0);
		}
		//订单服务器下单
		List<OrderBaseData> orderBaseDatas = new ArrayList<OrderBaseData>();
		//ChargeService("100001", "充电服务"),
		//CollectingElectricityFee("100002", "代收电费服务"),
		OrderBaseData orderBaseData_ChargeService = new OrderBaseData();
		if(userCard.startsWith("18808")&&!userCard.substring(0, 9).equals("188089999")){
			orderBaseData_ChargeService.setAppId(BizSystemCode.DzApp.value());
		}
//		orderBaseData.setAppId("");
//		orderBaseData.setAuxEquipmentNo("");
		orderBaseData_ChargeService.setBuyNum(BigDecimal.valueOf(this_reading));
		orderBaseData_ChargeService.setCardNo(userCard);
		orderBaseData_ChargeService.setCardType(map.get("cardType"));
		orderBaseData_ChargeService.setStartTime(omsChargerChargeBillRecord.getStart_time());
		orderBaseData_ChargeService.setEndTime(omsChargerChargeBillRecord.getEnd_time());
		orderBaseData_ChargeService.setEquipmentNo(chargerId);
//		orderBaseData_ChargeService.setMerchantCode(omsCharger.getOper_merchant_id());
		if(omsStation!=null){
			orderBaseData_ChargeService.setPlantName(omsStation.getStation_name());
		}		
		orderBaseData_ChargeService.setPlantId(omsCharger.getStation_id());
		orderBaseData_ChargeService.setServiceNo(OrderServiceEnum.ChargeService.value());
		orderBaseData_ChargeService.setServiceProviderCode(omsCharger.getOper_merchant_id());
		orderBaseData_ChargeService.setTotalPrice(BigDecimal.valueOf(char_bill));
		orderBaseData_ChargeService.setAuxEquipmentNo("0");
//		orderBaseData_ChargeService.setUnitPrice("");
//		orderBaseData.setUserId("");
//		orderBaseData.setUserType("");
		//TODO
//		orderBaseData.setWhiteListInfo("");
		//TODO
//		orderBaseData.setDivideInfo("");
		
		OrderBaseData orderBaseData_Chargefee = new OrderBaseData();
		if(userCard.startsWith("18808")&&!userCard.substring(0, 9).equals("188089999")){
			orderBaseData_Chargefee.setAppId(BizSystemCode.DzApp.value());
		}
//		orderBaseData.setAppId("");
//		orderBaseData.setAuxEquipmentNo("");
		orderBaseData_Chargefee.setBuyNum(BigDecimal.valueOf(this_reading));
		orderBaseData_Chargefee.setCardNo(userCard);
		orderBaseData_Chargefee.setCardType(map.get("cardType"));
		orderBaseData_Chargefee.setStartTime(omsChargerChargeBillRecord.getStart_time());
		orderBaseData_Chargefee.setEndTime(omsChargerChargeBillRecord.getEnd_time());
		orderBaseData_Chargefee.setEquipmentNo(chargerId);
//		orderBaseData_ChargeService.setMerchantCode(omsCharger.getOper_merchant_id());
		if(omsStation!=null){
			orderBaseData_Chargefee.setPlantName(omsStation.getStation_name());
		}		
		orderBaseData_Chargefee.setPlantId(omsCharger.getStation_id());
		orderBaseData_Chargefee.setServiceNo(OrderServiceEnum.CollectingElectricityFee.value());
		orderBaseData_Chargefee.setServiceProviderCode(omsCharger.getOper_merchant_id());
		orderBaseData_Chargefee.setTotalPrice(BigDecimal.valueOf(this_amount_before));
		orderBaseData_Chargefee.setAuxEquipmentNo("0");
//		orderBaseData_ChargeService.setUnitPrice("");
//		orderBaseData.setUserId("");
//		orderBaseData.setUserType("");
		//TODO
//		orderBaseData.setWhiteListInfo("");
		//TODO
//		orderBaseData.setDivideInfo("");
		orderBaseDatas.add(orderBaseData_ChargeService);
		orderBaseDatas.add(orderBaseData_Chargefee);
		//TODO 测试时屏蔽，正式时打开
//		RetVO retVO = orderRpcClient.createOrder(orderBaseDatas);
//		if(retVO==null||!retVO.getRetCode().equals(retVO.SuccessCode)){
//			json.setCode(retVO.FailCode);
//		    json.setMsg("createOrder fail");
//		    responseMsgHeader =data.substring(0, 34)+"55"+data.substring(36);
//		    json.setPojo(responseMsgHeader);
//		    return json;
//		}
//    	String bizData = (String) retVO.getBizData();
//    	CreatedOrderVO createdOrderVO = JSON.parseObject(bizData, CreatedOrderVO.class);
//		omsChargerChargeBillRecord.setThis_amount(Float.valueOf(createdOrderVO.getTotalFee().toString()));
		omsChargerChargeBillRecordDao.updateObject(omsChargerChargeBillRecord);
		String dzFun="&a=paycharge";
		//通知APP SERVER生成账单，账单生成后，如果是线上卡，则需要改写Offline_is_pay状态为4
//        requestURL = StringUtil.dzAppURL+dzFun+"&dianzhuanghao="+omsCharger.getQr_code()+"&user_pay_card="+userCard+"&start_em="+start_em+"&dianzhanid="+omsCharger.getStation_id()
//        		+"&end_em="+end_em+"&electric_charge="+this_amount_before+"&serve_charge="+char_bill+"&end_time="+now+"&charge_time="+charge_time;
//        StringUtil.httpGetRequest(requestURL);		
        responseMsgHeader =data.substring(0, 34)+"55"+data.substring(36,50);
        json.setCode("200");
        json.setMsg("ok");
        json.setPojo(responseMsgHeader);
		return json;
	
	}
	@SuppressWarnings({ "rawtypes", "unchecked", "unused" })
	private JsonCommon commonUploadBill(Map<String, String> map) throws Exception
	{
		log.info("Receive response message from uploadBill18805_0101 curTime = " + new Date().getTime());
		String data,chargerId,responseMsgHeader,requestURL; 
		data = map.get("data");
		responseMsgHeader = data.substring(0, 8) +"FFFFFF"+ data.substring(14, 34)+"55"+data.substring(36,50);
		
		JsonCommon json = new JsonCommon();
		String userCard = map.get("userCard");
		chargerId = map.get("chargerId");
		UploadBillProcess uploadBillProcess = BillProcessFactory.getBillProcessInstance(userCard);
		if(uploadBillProcess != null)
		map.put("user_pay_card", userCard);
//		map.put("service_payment", map.get("char_bill_id"));
//		map.put("reservation_fee", map.get("char_bill_id")); //*充电前电表读数 BIN码 4 系数为0.01 低字节在前，高字节在后，实际值X100上送
		map.put("charging_fee", map.get("this_amount")); //*本次充电金额  与上类似
		map.put("service_fee",  map.get("char_bill_id"));  // 本次充电金额BIN码
		
		OmsChargerChargeBillRecord billRecord_query = new OmsChargerChargeBillRecord();
		billRecord_query.setCharger_id(map.get("chargerId"));
		billRecord_query.setStatus(4);
		billRecord_query.setValid_flag(1);
//		billRecord_query.setOffline_is_pay(2);
		billRecord_query.setUser_pay_card(userCard);
		OmsChargerChargeBillRecord billRecord = omsChargerChargeBillRecordDao.findOneExample(billRecord_query,"start_time","desc");
		
		if (billRecord == null || billRecord.getMsg_charge_jrnl() == null) { // 根据卡号,支付状态,桩号,状态;查询无结果代表,该账单是脏数据,不做处理,返回错误码即可
			json.setCode("400");
			json.setMsg("uploadBill invalid! chargerId = " + chargerId + " userCard = " + userCard);
			json.setPojo(responseMsgHeader);
			log.debug("error OmsChargerChargeBillRecord findOneExample no data!");
			return json;
		}
		
		map.put("oms_msg_charge_jrnl", billRecord.getMsg_charge_jrnl()); // 之前充电的流水号
		
		try {
			log.info("Receive response message from uploadBill18805_0101 uploadBillProcess.ProcessBill start curTime = " + new Date().getTime());
			map = uploadBillProcess.ProcessBill(map);
			log.info("Receive response message from uploadBill18805_0101 uploadBillProcess.ProcessBill end curTime = " + new Date().getTime());
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			json.setCode("400");
			json.setMsg(e.getMessage());  
			return json;
		}
		
		responseMsgHeader = data.substring(0, 34) + "55" + data.substring(36, 50);
		return json;
		
		/*String data,chargerId,responseMsgHeader,requestURL; 
		JsonCommon json = new JsonCommon();
		data = map.get("data");
		chargerId = map.get("chargerId");
		OmsCharger omsCharger_query = new OmsCharger();
		omsCharger_query.setCharger_id(chargerId);
		OmsCharger omsCharger =omsChargerDao.findOneExample(omsCharger_query, null, null);
		if(omsCharger==null){
			json.setCode("10301201");
			json.setMsg("charge not found!");
			return json;
		}
		String start_time =map.get("start_time");
//		start_time =  StringUtil.time14format(start_time);
		Date start_time_date =StringUtil.StrToDate(start_time);
//		long start_time_long = new java.text.SimpleDateFormat ("yyyy-MM-dd HH:mm:ss").parse(start_time).getTime();
		String end_time =map.get("end_time");
//		Date end_time_date =  StringUtil.time14format(end_time);
		Date end_time_date =StringUtil.StrToDate(end_time);
//		long end_time_long = new java.text.SimpleDateFormat ("yyyy-MM-dd HH:mm:ss").parse(end_time).getTime();
//		long charge_time = end_time_long - start_time_long;
		String userCard =map.get("userCard");
		float start_em = StringUtil.float16to10ByParamDesc(data.substring(98,106), 100); //*充电前电表读数 BIN码 4 系数为0.01 低字节在前，高字节在后，实际值X100上送
		float end_em = StringUtil.float16to10ByParamDesc(data.substring(106,114), 100); //*充电后电表读数 BIN码 4 系数为0.01 低字节在前，高字节在后，实际值X100上送
		float this_reading = StringUtil.float16to10ByParamDesc(data.substring(114,122), 100);//*本次充电电量  与上类似
		float this_amount_before = StringUtil.float16to10ByParamDesc(data.substring(122,130), 100);//*本次充电金额  与上类似
		float offline_balance_start = StringUtil.float16to10ByParamDesc(data.substring(130,138), 100);//充电前卡余额  与上类似
		float offline_balance_end = StringUtil.float16to10ByParamDesc(data.substring(138,146), 100);//充电后卡余额  与上类似
		float char_bill = StringUtil.float16to10ByParamDesc(data.substring(146,150), 100);//服务费金额  2   与上类似
		String protocol_version = map.get("protocol_version");
		String offline_is_pay =data.substring(150, 152);//是否线下支付
		int offline_is_pay_int = Integer.valueOf(offline_is_pay,2);
//			0x01: 后台远程控制正常结束
//			0x02: 本地刷卡控制正常结束
//			0x03: 满足预设停止条件正常结束
//			0x04：电池满电正常结束
		OmsChargerChargeBillRecord  omsChargerChargeBillRecord_query  = new OmsChargerChargeBillRecord(); 
		omsChargerChargeBillRecord_query.setCharger_id(chargerId);
		omsChargerChargeBillRecord_query.setUser_pay_card(userCard);
		if(offline_is_pay_int==1){
			omsChargerChargeBillRecord_query.setOffline_is_pay(1);
		}else{
			omsChargerChargeBillRecord_query.setOffline_is_pay(0);
		}
		omsChargerChargeBillRecord_query.setStatus(4);//4 充电结束 ：桩回复充电结束 ；
		OmsChargerChargeBillRecord  omsChargerChargeBillRecord = omsChargerChargeBillRecordDao.findOneExample(omsChargerChargeBillRecord_query, "create_time", "desc");
		if(omsChargerChargeBillRecord==null){
			json.setCode("10301201");
			json.setMsg("charge bill record not found!");
			return json;
		}
		//查询卡号是不是在白名单里面。
		OmsChargerOfflineWhitelist whitelist_query = new OmsChargerOfflineWhitelist();
		whitelist_query.setCharger_id(chargerId);
		whitelist_query.setUser_pay_card(userCard);
		OmsChargerOfflineWhitelist whitelist = omsChargerOfflineWhitelistDao.findOneExample(whitelist_query, null, null);
		if(whitelist!=null){
			char_bill = 0;
			this_amount_before = 0;
		}
		Date now = new Date();
		omsChargerChargeBillRecord.setEnd_time(end_time_date);
		omsChargerChargeBillRecord.setStart_time(start_time_date);
		
//		long charge_time = now.getTime() - omsChargerChargeBillRecord.getStart_time().getTime();
		omsChargerChargeBillRecord.setStart_em(String.valueOf(start_em));
		omsChargerChargeBillRecord.setEnd_em(String.valueOf(end_em));
		omsChargerChargeBillRecord.setThis_reading(String.valueOf(this_reading));
		omsChargerChargeBillRecord.setThis_amount_before(this_amount_before);
		omsChargerChargeBillRecord.setThis_amount(this_amount_before);
		omsChargerChargeBillRecord.setChar_bill(char_bill);
//		omsChargerChargeBillRecord.setOffline_balance_start(String.valueOf(offline_balance_start));
		omsChargerChargeBillRecord.setOffline_balance_end(String.valueOf(offline_balance_end));
		omsChargerChargeBillRecord.setStatus(OmsConstant.ChargingBillStatus.BillGenerated);
		omsChargerChargeBillRecord.setValid_flag(1);
		omsChargerChargeBillRecord.setChar_bill(char_bill);
		omsChargerChargeBillRecord.setUser_pay_card(userCard);
		List<OrderBaseData> orderBaseDatas = new ArrayList<OrderBaseData>();
		//订单服务器下单
		//1 先查询数据库：  如果桩允许生成费用，则 2 数据库做记录；查询相关费率传总价给订单服务器，调用订单接口 3 返回json； 
		//如果桩不允许生成费用，则 查询单价 ，2 直接传总价给订单服务器，调用订单接口 ；数据库做记录3 返回json
		//通过桩查询服务费单价 TODO  oms_charger_rate[电桩费率表]  start_time  end_time
		float totalPrice = 0;
		if(omsCharger.getIs_allow_generate_fee()==1){
			int rate_schema = omsCharger.getRate_schema_charge_fee();
			OmsChargerRate omsChargerRate_query = new OmsChargerRate();
			omsChargerRate_query.setRate_schema(rate_schema);
			List<OmsChargerRate> omsChargerRateList =  chargerRateService.findExample(omsChargerRate_query);
			totalPrice = StringUtil.calculateTotalPrice(start_time,end_time,omsChargerRateList,this_amount_before);
		}else{
			totalPrice = this_amount_before;
		}
		//ChargeService("100001", "充电服务"),
		//CollectingElectricityFee("100002", "代收电费服务"),
		OrderBaseData orderBaseData_ChargeService = new OrderBaseData();
//		if(userCard.startsWith("18808")&&!userCard.substring(0, 9).equals("188089999")){
//			orderBaseData_ChargeService.setAppId(BizSystemCode.DzApp.value());
//		}
		orderBaseData_ChargeService.setAppId(BizSystemCode.DzApp.value()); // 充电服务:appId
		orderBaseData_ChargeService.setBuyNum(BigDecimal.valueOf(this_reading));
		orderBaseData_ChargeService.setCardNo(userCard);
		orderBaseData_ChargeService.setCardType(map.get("cardType"));
		orderBaseData_ChargeService.setStartTime(omsChargerChargeBillRecord.getStart_time());
		orderBaseData_ChargeService.setEndTime(omsChargerChargeBillRecord.getEnd_time());
		orderBaseData_ChargeService.setEquipmentNo(chargerId);
//		orderBaseData_ChargeService.setMerchantCode(omsCharger.getOper_merchant_id());
		orderBaseData_ChargeService.setPlantId(omsCharger.getStation_id());
		orderBaseData_ChargeService.setServiceNo(OrderServiceEnum.ChargeService.value());
		orderBaseData_ChargeService.setServiceProviderCode(omsCharger.getOper_merchant_id());
		orderBaseData_ChargeService.setTotalPrice(BigDecimal.valueOf(char_bill));
		orderBaseData_ChargeService.setAuxEquipmentNo("0");
		orderBaseData_ChargeService.setPayerBalance("0");
		
//		orderBaseData_ChargeService.setUnitPrice(null);
		if(!map.get("cardType").equals(CardType.ONLINE_CARD.value())){ // 处理线下卡(totalPrice)
			if(offline_is_pay_int==0){ // 是否线下支付(0x01:已线下支付  0x00 未支付 )
				orderBaseData_ChargeService.setTotalPrice(new BigDecimal(Float.toString(totalPrice)));
			}
		}
		// 处理分润规则信息:OS的分成类
		OrderBaseData.DivideInfo divideInfo = new OrderBaseData.DivideInfo();
		OmsServiceSplitratio serviceSplitratio_query = new OmsServiceSplitratio();
		serviceSplitratio_query.setCharger_id(chargerId);
		//		OmsServiceSplitratio serviceSplitratio = serviceSplitratioDaoImpl.
		String condition = " where scheme_no in (select scheme_no from oms_service_splitratio where service_no ='" + OrderConstant.OrderServiceEnum.ChargeService.value() + "' and charger_id = '" + chargerId + "')";
		List<OmsSplitratioScheme> list_omsServiceSplitratio = omsSplitratioSchemeDao.findListByCondition(new OmsSplitratioScheme(), condition);
		divideInfo.setKeyLink(chargerId);
		divideInfo.setPlantId(omsCharger.getStation_id());
		StringBuilder merchantCodes_sb = new StringBuilder("");
		StringBuilder ratios_sb = new StringBuilder("");
		StringBuilder minAmount_sb = new StringBuilder("");
		if (list_omsServiceSplitratio.size() > 0)
		{
			for (OmsSplitratioScheme scheme : list_omsServiceSplitratio)
			{
				merchantCodes_sb.append(scheme.getEntity_id() + ",");
				ratios_sb.append(scheme.getRatios() + ",");
				minAmount_sb.append(scheme.getMin_amount() + ",");
			}
			merchantCodes_sb.deleteCharAt(merchantCodes_sb.length() - 1);
			ratios_sb.deleteCharAt(ratios_sb.length() - 1);
			minAmount_sb.deleteCharAt(minAmount_sb.length() - 1);
			divideInfo.setMerchantCodes(merchantCodes_sb.toString());
			divideInfo.setRatios(ratios_sb.toString());
			divideInfo.setMinAmount(minAmount_sb.toString());
			//divideInfo.setMerchantCodes();
			orderBaseData_ChargeService.setDivideInfo(divideInfo);
		}
		OrderBaseData orderBaseData_Chargefee = new OrderBaseData();
//		if(userCard.startsWith("18808")&&!userCard.substring(0, 9).equals("188089999")){
//			orderBaseData_Chargefee.setAppId(BizSystemCode.DzApp.value());
//		}
		orderBaseData_Chargefee.setAppId(BizSystemCode.DzApp.value()); // 代收电费服务:appId
		orderBaseData_Chargefee.setBuyNum(BigDecimal.valueOf(this_reading));
		orderBaseData_Chargefee.setCardNo(userCard);
		orderBaseData_Chargefee.setCardType(map.get("cardType"));
		orderBaseData_Chargefee.setStartTime(omsChargerChargeBillRecord.getStart_time());
		orderBaseData_Chargefee.setEndTime(omsChargerChargeBillRecord.getEnd_time());
		orderBaseData_Chargefee.setEquipmentNo(chargerId);
		orderBaseData_Chargefee.setMerchantCode(omsCharger.getOper_merchant_id());
		orderBaseData_Chargefee.setPlantId(omsCharger.getStation_id());
		orderBaseData_Chargefee.setServiceNo(OrderServiceEnum.CollectingElectricityFee.value());
		orderBaseData_Chargefee.setServiceProviderCode(omsCharger.getOper_merchant_id());
		orderBaseData_Chargefee.setTotalPrice(BigDecimal.valueOf(this_amount_before));
		orderBaseData_Chargefee.setAuxEquipmentNo("0");
		orderBaseData_ChargeService.setPayerBalance("0");
		if(!map.get("cardType").equals(CardType.ONLINE_CARD.value())){ // 处理线下卡(totalPrice)
			if(offline_is_pay_int==0){ // 是否线下支付(0x01:已线下支付  0x00 未支付 )
				orderBaseData_Chargefee.setTotalPrice(new BigDecimal(Float.toString(totalPrice)));
			}
		}
		orderBaseDatas.add(orderBaseData_ChargeService);
		orderBaseDatas.add(orderBaseData_Chargefee);
		
		//TODO 测试时屏蔽,正式时打开
		try {
			RetVO retVO = orderRpcClient.createOrder(orderBaseDatas);
			if (retVO == null || !retVO.getRetCode().equals(RetVO.SuccessCode)) {
				log.debug("error on calling order server");
			    json.setMsg("createOrder fail");
			    responseMsgHeader =data.substring(0, 34)+"55"+data.substring(36,50);
			    json.setPojo(responseMsgHeader);
			    return json;
			}
			//			String bizData = retVO.getBizData().toString();
			//			log.debug(bizData);
			//			CreateOrderReturnVO.CreatedOrderVO createdOrderVO = retVO.getBizData();
			String bizData = retVO.getBizData().toString();
			log.debug(bizData);
			RetVO.CreatedOrderVO createdOrderVO = JSON.parseObject(bizData, RetVO.CreatedOrderVO.class);
			omsChargerChargeBillRecord.setThis_amount(Float.valueOf(createdOrderVO.getTotalFee().toString()));
			omsChargerChargeBillRecord.setOrder_no(createdOrderVO.getOrderNo());
			omsChargerChargeBillRecordDao.updateObject(omsChargerChargeBillRecord);
			//		String dzFun="&a=paycharge";
			//通知APP SERVER生成账单，账单生成后，如果是线上卡，则需要改写Offline_is_pay状态为4
			//        requestURL = StringUtil.dzAppURL+dzFun+"&dianzhuanghao="+omsCharger.getQr_code()+"&user_pay_card="+userCard+"&start_em="+start_em+"&dianzhanid="+omsCharger.getStation_id()
			//        		+"&end_em="+end_em+"&electric_charge="+this_amount_before+"&serve_charge="+char_bill+"&end_time="+StringUtil.now14time()+"&charge_time="+charge_time;
			//        StringUtil.httpGetRequest(requestURL);
			//        responseMsgHeader =data.substring(0, 34)+"55"+data.substring(36);
			responseMsgHeader =data.substring(0, 34)+"55"+data.substring(36,50);
			
			// 通知appServer start
			String orderNo = JSON.parseObject(bizData, RetVO.CreatedOrderVO.class).getOrderNo(); // 订单编号
			String money = JSON.parseObject(bizData, RetVO.CreatedOrderVO.class).getTotalFee().toString(); // 实付金额
	        AppOrderNotifyParam appOrderNotifyParam= new AppOrderNotifyParam();
			// 通知appServer end
			appOrderNotifyParam.setUserCard(userCard);
			appOrderNotifyParam.setOrderNo(orderNo);
			appOrderNotifyParam.setMoney(money);
			json = systemAppServerRpcClient.orderNotify(appOrderNotifyParam);
			// 通知appServer end
			
//	        json.setCode("200");
//	        json.setMsg("ok");
	        json.setPojo(responseMsgHeader);
			return json;			
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw e;
		}
		
		//TODO 测试时屏蔽，正式时打开
		RetVO retVO = orderRpcClient.createOrder(orderBaseDatas);
		if(retVO==null||!retVO.getRetCode().equals(retVO.SuccessCode)){
			json.setCode(retVO.FailCode);
		    json.setMsg("createOrder fail");
		    responseMsgHeader =data.substring(0, 34)+"55"+data.substring(36);
		    json.setPojo(responseMsgHeader);
		    return json;
		}
//    	String bizData = (String) retVO.getBizData();
//    	CreatedOrderVO createdOrderVO = JSON.parseObject(bizData, CreatedOrderVO.class);
//		omsChargerChargeBillRecord.setThis_amount(Float.valueOf(createdOrderVO.getTotalFee().toString()));
		omsChargerChargeBillRecordDao.updateObject(omsChargerChargeBillRecord);
		String dzFun="&a=paycharge";
		//通知APP SERVER生成账单，账单生成后，如果是线上卡，则需要改写Offline_is_pay状态为4
        requestURL = StringUtil.dzAppURL+dzFun+"&dianzhuanghao="+omsCharger.getQr_code()+"&user_pay_card="+userCard+"&start_em="+start_em+"&dianzhanid="+omsCharger.getStation_id()
        		+"&end_em="+end_em+"&electric_charge="+this_amount_before+"&serve_charge="+char_bill+"&end_time="+now+"&charge_time="+charge_time;
        StringUtil.httpGetRequest(requestURL);		
        responseMsgHeader =data.substring(0, 34)+"55"+data.substring(36);
        json.setCode("200");
        json.setMsg("ok");
        json.setPojo(responseMsgHeader);
		return json;			*/
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon uploadBill188089999_0101(Map<String, String> map) throws Exception
	{
		return commonUploadBill(map);
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon uploadBill18808_0101(Map<String, String> map) throws Exception
	{
		return commonUploadBill(map);
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon uploadBill0103(Map<String, String> map)  throws ParseException, OmsDaoException{
		JsonCommon json = new JsonCommon();
		String data = map.get("data");
		String userCard =data.substring(78, 98);
		// 如果是线下充值卡，就 1 数据库做记录，2  不传单价给订单服务器，调用订单接口 3 返回json
		if(userCard.startsWith("18806")){
			map.put("cardType", CardType.OFFLINE_CARD.value());
			json = uploadBill18806(map);
		}
		// 如果是线下卡（身份认证卡） ,则1 先查询数据库：  如果桩允许生成费用，则 2 数据库做记录；查询相关费率传总价给订单服务器，调用订单接口 3 返回json； 
		//如果桩不允许生成费用，则 查询单价 ，2 直接传总价给订单服务器，调用订单接口 ；数据库做记录3 返回json
		if(userCard.startsWith("18805")){
			map.put("cardType", CardType.IDENTITY_CARD.value());
			json = uploadBill18805(map);
		}
		// 如果是线上卡app用户，,则1 先查询数据库：  如果桩允许生成费用，则 2 数据库做记录；查询相关费率传总价给订单服务器，调用订单接口 3 返回json； 
		//如果桩不允许生成费用，则 查询单价 ，2 直接传总价给订单服务器，调用订单接口 ；数据库做记录3 返回json
		if(userCard.startsWith("18808")&&!userCard.substring(0, 9).equals("188089999")){
			map.put("cardType", CardType.ONLINE_CARD.value());
			json = uploadBill188089999(map);
		}
		// 如果是线上卡企业用户，,则1 先查询数据库：  如果桩允许生成费用，则 2 数据库做记录；查询相关费率传总价给订单服务器，调用订单接口 3 返回json； 
		//如果桩不允许生成费用，则 查询单价 ，2 直接传总价给订单服务器，调用订单接口 ；数据库做记录3 返回json
		if(userCard.startsWith("18808")){
			map.put("cardType", CardType.ONLINE_CARD.value());
			json = uploadBill18808(map);
		}
		return json;
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon uploadBill18808(Map<String, String> map) throws ParseException, OmsDaoException{
		return uploadBill18805(map);
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon uploadBill188089999(Map<String, String> map) throws ParseException, OmsDaoException{
		return uploadBill18805(map);
	}
	@SuppressWarnings({ "rawtypes", "static-access", "unchecked" })
	private JsonCommon uploadBill18805(Map<String, String> map) throws ParseException, OmsDaoException {
		String data,chargerId,responseMsgHeader,requestURL; 
		JsonCommon json = new JsonCommon();
		data = map.get("data");
		chargerId = map.get("chargerId");
		OmsCharger omsCharger_query = new OmsCharger();
		OmsCharger omsCharger =omsChargerDao.findOneExample(omsCharger_query, null, null);
		if(omsCharger==null){
			json.setCode("10301201");
			json.setMsg("charge not found!");
			return json;
		}
		OmsStation omsStaionQuery = new OmsStation(omsCharger.getStation_id());
		OmsStation omsStation = omsStationDao.findRecordByPK(omsStaionQuery);
		String start_time =map.get("start_time");
		Date start_time_date =StringUtil.StrToDate(start_time);
		String end_time =map.get("end_time");
		Date end_time_date =StringUtil.StrToDate(end_time);
		String userCard =map.get("userCard");
		float start_em = StringUtil.float16to10ByParamDesc(data.substring(98,106), 100); //*充电前电表读数 BIN码 4 系数为0.01 低字节在前，高字节在后，实际值X100上送
		float end_em = StringUtil.float16to10ByParamDesc(data.substring(106,114), 100); //*充电后电表读数 BIN码 4 系数为0.01 低字节在前，高字节在后，实际值X100上送
		float this_reading = StringUtil.float16to10ByParamDesc(data.substring(114,122), 100);//*本次充电电量  与上类似
		float this_amount_before = StringUtil.float16to10ByParamDesc(data.substring(122,130), 100);//*本次充电金额  与上类似
		float offline_balance_start = StringUtil.float16to10ByParamDesc(data.substring(130,138), 100);//充电前卡余额  与上类似
		float offline_balance_end = StringUtil.float16to10ByParamDesc(data.substring(138,146), 100);//充电后卡余额  与上类似
		float char_bill = StringUtil.float16to10ByParamDesc(data.substring(146,150), 100);//服务费金额  2   与上类似
		String protocol_version = map.get("protocol_version");
		String org_serial_no =data.substring(150, 164);//之前充电的流水号
		String offline_is_pay =data.substring(164, 166);//是否线下支付
		int offline_is_pay_int = Integer.valueOf(offline_is_pay,2);
		String charge_end_reason =data.substring(166, 168);//充电结束原因
//			0x01: 后台远程控制正常结束
//			0x02: 本地刷卡控制正常结束
//			0x03: 满足预设停止条件正常结束
//			0x04：电池满电正常结束
		String charge_start_mode = data.substring(168, 170);//充电启动方式 0x00：后台远程启动 0x01: 本地刷卡远程验证启动  0x02：本地刷卡白名单验证启动
		String control_type = data.substring(170, 172);//控制类型  参考控制类型表对应数据，如0x04为自动充满方式。
		String open_restricted_data = data.substring(172, 180);//开启限制数据  自动充满停机方式下无意义。低字节在前，高字节在后。电量控制,单位为“度”，精确到0.01,传输数据放大100倍；时间控制，单位为“秒“，精确到1,；金额控制，单位为“元”，精确到0.01，传输数据放大100倍。
		float open_restricted_data_float = 0;
		String control_type_stop_condition = control_type.substring(1, 2);
		switch(control_type_stop_condition){
			case "1"://电量控制充电  电量控制,单位为“度”，精确到0.01,传输数据放大100倍；
				open_restricted_data_float = StringUtil.float16to10ByParamDesc(open_restricted_data, 100);
				break;
			case "2"://时间控制充电 时间控制，单位为“秒“，精确到1,
				open_restricted_data_float = StringUtil.float16to10ByParamDesc(open_restricted_data, 1);
				break;
			case "3"://金额控制充电  金额控制，单位为“元”，精确到0.01，传输数据放大100倍。
				open_restricted_data_float = StringUtil.float16to10ByParamDesc(open_restricted_data, 100);
				break;
			case "4"://自动充满为止
				break;
			default:
				break;
		}
		String vehicle_identification_code = data.substring(180, 214);//车辆识别码
		OmsChargerChargeBillRecord  omsChargerChargeBillRecord_query  = new OmsChargerChargeBillRecord(); 
//			omsChargerChargeBillRecord_query.setCharger_id(chargerId);
//			omsChargerChargeBillRecord_query.setUser_pay_card(userCard);
//			if(offline_is_pay_int==1){
//				omsChargerChargeBillRecord_query.setOffline_is_pay(1);
//			}else{
//				omsChargerChargeBillRecord_query.setOffline_is_pay(0);
//			}
//			omsChargerChargeBillRecord_query.setStatus(4);//4 充电结束 ：桩回复充电结束 ；
		omsChargerChargeBillRecord_query.setCharge_jrnl(org_serial_no);
		OmsChargerChargeBillRecord  omsChargerChargeBillRecord = omsChargerChargeBillRecordDao.findOneExample(omsChargerChargeBillRecord_query, "create_time", "desc");
		if(omsChargerChargeBillRecord==null){
			json.setCode("10301201");
			json.setMsg("charge bill record not found!");
			return json;
		}		
		//查询卡号是不是在白名单里面。
		OmsChargerOfflineWhitelist whitelist_query = new OmsChargerOfflineWhitelist();
		whitelist_query.setCharger_id(chargerId);
		whitelist_query.setUser_pay_card(userCard);
		OmsChargerOfflineWhitelist whitelist = omsChargerOfflineWhitelistDao.findOneExample(whitelist_query, null, null);
		if(whitelist!=null){
			char_bill = 0;
			this_amount_before = 0;
		}
		Date now = new Date();
		omsChargerChargeBillRecord.setEnd_time(end_time_date);
		omsChargerChargeBillRecord.setStart_time(start_time_date);
		
		long charge_time = now.getTime() - omsChargerChargeBillRecord.getStart_time().getTime();
		omsChargerChargeBillRecord.setStart_em(String.valueOf(start_em));
		omsChargerChargeBillRecord.setEnd_em(String.valueOf(end_em));
		omsChargerChargeBillRecord.setThis_reading(String.valueOf(this_reading));
		omsChargerChargeBillRecord.setThis_amount_before(this_amount_before);
		omsChargerChargeBillRecord.setThis_amount(this_amount_before);
		omsChargerChargeBillRecord.setChar_bill(char_bill);
		omsChargerChargeBillRecord.setOffline_balance_start(String.valueOf(offline_balance_start));
		omsChargerChargeBillRecord.setOffline_balance_end(String.valueOf(offline_balance_end));
		omsChargerChargeBillRecord.setStatus(5);
		omsChargerChargeBillRecord.setValid_flag(1);
		omsChargerChargeBillRecord.setCharge_start_mode(charge_start_mode);
		omsChargerChargeBillRecord.setChar_bill(char_bill);
		omsChargerChargeBillRecord.setCharge_end_reason(charge_end_reason);
		omsChargerChargeBillRecord.setControl_type(control_type);
		omsChargerChargeBillRecord.setOpen_restricted_data(String.valueOf(open_restricted_data_float));
		omsChargerChargeBillRecord.setVIN(vehicle_identification_code);
		omsChargerChargeBillRecord.setUser_pay_card(userCard);
		List<OrderBaseData> orderBaseDatas = new ArrayList<OrderBaseData>();
		//订单服务器下单
		//1 先查询数据库：  如果桩允许生成费用，则 2 数据库做记录；查询相关费率传总价给订单服务器，调用订单接口 3 返回json； 
		//如果桩不允许生成费用，则 查询单价 ，2 直接传总价给订单服务器，调用订单接口 ；数据库做记录3 返回json
		//通过桩查询服务费单价 TODO  oms_charger_rate[电桩费率表]  start_time  end_time
		float totalPrice = 0;
		if(omsCharger.getIs_allow_generate_fee()==1){
			int rate_schema = omsCharger.getRate_schema_charge_fee();
			OmsChargerRate omsChargerRate_query = new OmsChargerRate();
			omsChargerRate_query.setRate_schema(rate_schema);
			List<OmsChargerRate> omsChargerRateList =  chargerRateService.findExample(omsChargerRate_query);
			totalPrice = StringUtil.calculateTotalPrice(start_time,end_time,omsChargerRateList,this_amount_before);
		}else{
			totalPrice = this_amount_before;
		}
		//ChargeService("100001", "充电服务"),
		//CollectingElectricityFee("100002", "代收电费服务"),
		OrderBaseData orderBaseData_ChargeService = new OrderBaseData();
		if(userCard.startsWith("18808")&&!userCard.substring(0, 9).equals("188089999")){
			orderBaseData_ChargeService.setAppId(BizSystemCode.DzApp.value());
		}
		orderBaseData_ChargeService.setBuyNum(BigDecimal.valueOf(this_reading));
		orderBaseData_ChargeService.setCardNo(userCard);
		orderBaseData_ChargeService.setCardType(map.get("cardType"));
		orderBaseData_ChargeService.setStartTime(omsChargerChargeBillRecord.getStart_time());
		orderBaseData_ChargeService.setEndTime(omsChargerChargeBillRecord.getEnd_time());
		orderBaseData_ChargeService.setEquipmentNo(chargerId);
		if(omsStation!=null){
			orderBaseData_ChargeService.setPlantName(omsStation.getStation_name());
		}		
		orderBaseData_ChargeService.setPlantId(omsCharger.getStation_id());
		orderBaseData_ChargeService.setServiceNo(OrderServiceEnum.ChargeService.value());
		orderBaseData_ChargeService.setServiceProviderCode(omsCharger.getOper_merchant_id());
		orderBaseData_ChargeService.setUnitPrice(null);
		orderBaseData_ChargeService.setAuxEquipmentNo("0");
		//TODO
//				orderBaseData.setWhiteListInfo("");
		//TODO
//				orderBaseData.setDivideInfo("");
		OrderBaseData orderBaseData_Chargefee = new OrderBaseData();
		if(userCard.startsWith("18808")&&!userCard.substring(0, 9).equals("188089999")){
			orderBaseData_Chargefee.setAppId(BizSystemCode.DzApp.value());
		}
		orderBaseData_Chargefee.setBuyNum(BigDecimal.valueOf(this_reading));
		orderBaseData_Chargefee.setCardNo(userCard);
		orderBaseData_Chargefee.setCardType(map.get("cardType"));
		orderBaseData_Chargefee.setStartTime(omsChargerChargeBillRecord.getStart_time());
		orderBaseData_Chargefee.setEndTime(omsChargerChargeBillRecord.getEnd_time());
		orderBaseData_Chargefee.setEquipmentNo(chargerId);
//				orderBaseData_ChargeService.setMerchantCode(omsCharger.getOper_merchant_id());
		if(omsStation!=null){
			orderBaseData_Chargefee.setPlantName(omsStation.getStation_name());
		}		
		orderBaseData_Chargefee.setPlantId(omsCharger.getStation_id());
		orderBaseData_Chargefee.setServiceNo(OrderServiceEnum.CollectingElectricityFee.value());
		orderBaseData_Chargefee.setServiceProviderCode(omsCharger.getOper_merchant_id());
		orderBaseData_Chargefee.setTotalPrice(BigDecimal.valueOf(totalPrice));
		orderBaseData_Chargefee.setAuxEquipmentNo("0");
		//TODO
//				orderBaseData.setWhiteListInfo("");
		//TODO
//				orderBaseData.setDivideInfo("");
		orderBaseDatas.add(orderBaseData_ChargeService);
		orderBaseDatas.add(orderBaseData_Chargefee);
		//TODO 测试时屏蔽，正式时打开
//		RetVO retVO = orderRpcClient.createOrder(orderBaseDatas);
//		if(retVO==null||!retVO.getRetCode().equals(retVO.SuccessCode)){
//			json.setCode(retVO.FailCode);
//		    json.setMsg("createOrder fail");
//		    responseMsgHeader =data.substring(0, 34)+"55"+data.substring(36);
//		    json.setPojo(responseMsgHeader);
//		    return json;
//		}
//    	String bizData = (String) retVO.getBizData();
//    	CreatedOrderVO createdOrderVO = JSON.parseObject(bizData, CreatedOrderVO.class);
//		omsChargerChargeBillRecord.setThis_amount(Float.valueOf(createdOrderVO.getTotalFee().toString()));
		omsChargerChargeBillRecordDao.updateObject(omsChargerChargeBillRecord);
		String dzFun="&a=paycharge";
		//通知APP SERVER生成账单，账单生成后，如果是线上卡，则需要改写Offline_is_pay状态为4
//        requestURL = StringUtil.dzAppURL+dzFun+"&dianzhuanghao="+omsCharger.getQr_code()+"&user_pay_card="+userCard+"&start_em="+start_em+"&dianzhanid="+omsCharger.getStation_id()
//        		+"&end_em="+end_em+"&electric_charge="+this_amount_before+"&serve_charge="+char_bill+"&end_time="+now+"&charge_time="+charge_time;
//        StringUtil.httpGetRequest(requestURL);		
        responseMsgHeader =data.substring(0, 34)+"55"+data.substring(36);
        json.setCode("200");
        json.setMsg("ok");
        json.setPojo(responseMsgHeader);
		return json;			
	}

	@SuppressWarnings({ "rawtypes", "unchecked", "static-access" })
	private JsonCommon uploadBill18806(Map<String, String> map) throws OmsDaoException {
		//如果是线下充值卡，就 1 数据库做记录，2  不传单价给订单服务器，调用订单接口 3 返回json
		String data,chargerId,responseMsgHeader,requestURL; 
		JsonCommon json = new JsonCommon();
		data = map.get("data");
		chargerId = map.get("chargerId");
		OmsCharger omsCharger_query = new OmsCharger();
		OmsCharger omsCharger =omsChargerDao.findOneExample(omsCharger_query, null, null);
		if(omsCharger==null){
			json.setCode("10301201");
			json.setMsg("charge not found!");
			return json;
		}
		OmsStation omsStationQuery = new OmsStation(omsCharger.getStation_id());
		OmsStation omsStation = omsStationDao.findRecordByPK(omsStationQuery);

		String start_time =data.substring(50, 64);
		Date start_time_date =StringUtil.StrToDate(start_time);
//		start_time =  StringUtil.time14format(start_time);
//		long start_time_long = new java.text.SimpleDateFormat ("yyyy-MM-dd HH:mm:ss").parse(start_time).getTime();
		String end_time =data.substring(64, 78);
//		Date end_time_date =  StringUtil.time14format(end_time);
		Date end_time_date =StringUtil.StrToDate(end_time);
//		long end_time_long = new java.text.SimpleDateFormat ("yyyy-MM-dd HH:mm:ss").parse(end_time).getTime();
//		long charge_time = end_time_long - start_time_long;
		String userCard =data.substring(78, 98);
		float start_em = StringUtil.float16to10ByParamDesc(data.substring(98,106), 100); //*充电前电表读数 BIN码 4 系数为0.01 低字节在前，高字节在后，实际值X100上送
		float end_em = StringUtil.float16to10ByParamDesc(data.substring(106,114), 100); //*充电后电表读数 BIN码 4 系数为0.01 低字节在前，高字节在后，实际值X100上送
		float this_reading = StringUtil.float16to10ByParamDesc(data.substring(114,122), 100);//*本次充电电量  与上类似
		float this_amount_before = StringUtil.float16to10ByParamDesc(data.substring(122,130), 100);//*本次充电金额  与上类似
		float offline_balance_start = StringUtil.float16to10ByParamDesc(data.substring(130,138), 100);//充电前卡余额  与上类似
		float offline_balance_end = StringUtil.float16to10ByParamDesc(data.substring(138,146), 100);//充电后卡余额  与上类似
		float char_bill = StringUtil.float16to10ByParamDesc(data.substring(146,150), 100);//服务费金额  2   与上类似
		String protocol_version = map.get("protocol_version");
		String org_serial_no =data.substring(150, 164);//之前充电的流水号
		String offline_is_pay =data.substring(164, 166);//是否线下支付
		int offline_is_pay_int = Integer.valueOf(offline_is_pay,2);
		String charge_end_reason =data.substring(166, 168);//充电结束原因
//			0x01: 后台远程控制正常结束
//			0x02: 本地刷卡控制正常结束
//			0x03: 满足预设停止条件正常结束
//			0x04：电池满电正常结束
		String charge_start_mode = data.substring(168, 170);//充电启动方式 0x00：后台远程启动 0x01: 本地刷卡远程验证启动  0x02：本地刷卡白名单验证启动
		String control_type = data.substring(170, 172);//控制类型  参考控制类型表对应数据，如0x04为自动充满方式。
		String open_restricted_data = data.substring(172, 180);//开启限制数据  自动充满停机方式下无意义。低字节在前，高字节在后。电量控制,单位为“度”，精确到0.01,传输数据放大100倍；时间控制，单位为“秒“，精确到1,；金额控制，单位为“元”，精确到0.01，传输数据放大100倍。
		float open_restricted_data_float = 0;
		String control_type_stop_condition = control_type.substring(1, 2);
		switch(control_type_stop_condition){
			case "1"://电量控制充电  电量控制,单位为“度”，精确到0.01,传输数据放大100倍；
				open_restricted_data_float = StringUtil.float16to10ByParamDesc(open_restricted_data, 100);
				break;
			case "2"://时间控制充电 时间控制，单位为“秒“，精确到1,
				open_restricted_data_float = StringUtil.float16to10ByParamDesc(open_restricted_data, 1);
				break;
			case "3"://金额控制充电  金额控制，单位为“元”，精确到0.01，传输数据放大100倍。
				open_restricted_data_float = StringUtil.float16to10ByParamDesc(open_restricted_data, 100);
				break;
			case "4"://自动充满为止
				break;
			default:
				break;
		}
		String vehicle_identification_code = data.substring(180, 214);//车辆识别码
		OmsChargerChargeBillRecord  omsChargerChargeBillRecord_query  = new OmsChargerChargeBillRecord(); 
//		omsChargerChargeBillRecord_query.setCharger_id(chargerId);
//		omsChargerChargeBillRecord_query.setUser_pay_card(userCard);
//		//线上卡是18808开头  线下卡是18806开头
//		if(offline_is_pay_int==1){
//			omsChargerChargeBillRecord_query.setOffline_is_pay(1);
//		}else{
//			omsChargerChargeBillRecord_query.setOffline_is_pay(0);
//		}
//		omsChargerChargeBillRecord_query.setStatus(4);//4 充电结束 ：桩回复充电结束 ；
		omsChargerChargeBillRecord_query.setCharge_jrnl(org_serial_no);
		OmsChargerChargeBillRecord  omsChargerChargeBillRecord = omsChargerChargeBillRecordDao.findOneExample(omsChargerChargeBillRecord_query, "create_time", "desc");
		if(omsChargerChargeBillRecord==null){
			json.setCode("10301201");
			json.setMsg("charge bill record org_serial_no not found!");
			return json;
		}
		//查询卡号是不是在白名单里面。
		OmsChargerOfflineWhitelist whitelist_query = new OmsChargerOfflineWhitelist();
		whitelist_query.setCharger_id(chargerId);
		whitelist_query.setUser_pay_card(userCard);
		OmsChargerOfflineWhitelist whitelist = omsChargerOfflineWhitelistDao.findOneExample(whitelist_query, null, null);
		if(whitelist!=null){
			char_bill = 0;
			this_amount_before = 0;
		}
		Date now = new Date();
		omsChargerChargeBillRecord.setEnd_time(end_time_date);
		omsChargerChargeBillRecord.setStart_time(start_time_date);
		
		long charge_time = now.getTime() - omsChargerChargeBillRecord.getStart_time().getTime();
		omsChargerChargeBillRecord.setStart_em(String.valueOf(start_em));
		omsChargerChargeBillRecord.setEnd_em(String.valueOf(end_em));
		omsChargerChargeBillRecord.setThis_reading(String.valueOf(this_reading));
		omsChargerChargeBillRecord.setThis_amount_before(this_amount_before);
		omsChargerChargeBillRecord.setThis_amount(this_amount_before);
		omsChargerChargeBillRecord.setChar_bill(char_bill);
		omsChargerChargeBillRecord.setOffline_balance_start(String.valueOf(offline_balance_start));
		omsChargerChargeBillRecord.setOffline_balance_end(String.valueOf(offline_balance_end));
		omsChargerChargeBillRecord.setStatus(5);
		omsChargerChargeBillRecord.setValid_flag(1);
		omsChargerChargeBillRecord.setCharge_start_mode(charge_start_mode);
		omsChargerChargeBillRecord.setChar_bill(char_bill);
		omsChargerChargeBillRecord.setCharge_end_reason(charge_end_reason);
		omsChargerChargeBillRecord.setControl_type(control_type);
		omsChargerChargeBillRecord.setOpen_restricted_data(open_restricted_data);
		omsChargerChargeBillRecord.setVIN(vehicle_identification_code);
		omsChargerChargeBillRecord.setUser_pay_card(userCard);
		//订单服务器下单
		List<OrderBaseData> orderBaseDatas = new ArrayList<OrderBaseData>();
		//ChargeService("100001", "充电服务"),
		//CollectingElectricityFee("100002", "代收电费服务"),
		OrderBaseData orderBaseData_ChargeService = new OrderBaseData();
		if(userCard.startsWith("18808")&&!userCard.substring(0, 9).equals("188089999")){
			orderBaseData_ChargeService.setAppId(BizSystemCode.DzApp.value());
		}
//		orderBaseData.setAppId("");
//		orderBaseData.setAuxEquipmentNo("");
		orderBaseData_ChargeService.setBuyNum(BigDecimal.valueOf(this_reading));
		orderBaseData_ChargeService.setCardNo(userCard);
		orderBaseData_ChargeService.setCardType(map.get("cardType"));
		orderBaseData_ChargeService.setStartTime(omsChargerChargeBillRecord.getStart_time());
		orderBaseData_ChargeService.setEndTime(omsChargerChargeBillRecord.getEnd_time());
		orderBaseData_ChargeService.setEquipmentNo(chargerId);
//		orderBaseData_ChargeService.setMerchantCode(omsCharger.getOper_merchant_id());
		if(omsStation!=null){
			orderBaseData_ChargeService.setPlantName(omsStation.getStation_name());
		}		
		orderBaseData_ChargeService.setPlantId(omsCharger.getStation_id());
		orderBaseData_ChargeService.setServiceNo(OrderServiceEnum.ChargeService.value());
		orderBaseData_ChargeService.setServiceProviderCode(omsCharger.getOper_merchant_id());
		orderBaseData_ChargeService.setTotalPrice(BigDecimal.valueOf(char_bill));
		orderBaseData_ChargeService.setAuxEquipmentNo("0");
//		orderBaseData_ChargeService.setUnitPrice("");
//		orderBaseData.setUserId("");
//		orderBaseData.setUserType("");
		//TODO
//		orderBaseData.setWhiteListInfo("");
		//TODO
//		orderBaseData.setDivideInfo("");
		
		OrderBaseData orderBaseData_Chargefee = new OrderBaseData();
		if(userCard.startsWith("18808")&&!userCard.substring(0, 9).equals("188089999")){
			orderBaseData_Chargefee.setAppId(BizSystemCode.DzApp.value());
		}
//		orderBaseData.setAppId("");
//		orderBaseData.setAuxEquipmentNo("");
		orderBaseData_Chargefee.setBuyNum(BigDecimal.valueOf(this_reading));
		orderBaseData_Chargefee.setCardNo(userCard);
		orderBaseData_Chargefee.setCardType(map.get("cardType"));
		orderBaseData_Chargefee.setStartTime(omsChargerChargeBillRecord.getStart_time());
		orderBaseData_Chargefee.setEndTime(omsChargerChargeBillRecord.getEnd_time());
		orderBaseData_Chargefee.setEquipmentNo(chargerId);
//		orderBaseData_ChargeService.setMerchantCode(omsCharger.getOper_merchant_id());
		if(omsStation!=null){
			orderBaseData_Chargefee.setPlantName(omsStation.getStation_name());
		}		
		orderBaseData_Chargefee.setPlantId(omsCharger.getStation_id());
		orderBaseData_Chargefee.setServiceNo(OrderServiceEnum.CollectingElectricityFee.value());
		orderBaseData_Chargefee.setServiceProviderCode(omsCharger.getOper_merchant_id());
		orderBaseData_Chargefee.setTotalPrice(BigDecimal.valueOf(this_amount_before));
		orderBaseData_Chargefee.setAuxEquipmentNo("0");
//		orderBaseData_ChargeService.setUnitPrice("");
//		orderBaseData.setUserId("");
//		orderBaseData.setUserType("");
		//TODO
//		orderBaseData.setWhiteListInfo("");
		//TODO
//		orderBaseData.setDivideInfo("");
		orderBaseDatas.add(orderBaseData_ChargeService);
		orderBaseDatas.add(orderBaseData_Chargefee);
		//TODO 测试时屏蔽，正式时打开
//		RetVO retVO = orderRpcClient.createOrder(orderBaseDatas);
//		if(retVO==null||!retVO.getRetCode().equals(retVO.SuccessCode)){
//			json.setCode(retVO.FailCode);
//		    json.setMsg("createOrder fail");
//		    responseMsgHeader =data.substring(0, 34)+"55"+data.substring(36);
//		    json.setPojo(responseMsgHeader);
//		    return json;
//		}
//    	String bizData = (String) retVO.getBizData();
//    	CreatedOrderVO createdOrderVO = JSON.parseObject(bizData, CreatedOrderVO.class);
//		omsChargerChargeBillRecord.setThis_amount(Float.valueOf(createdOrderVO.getTotalFee().toString()));
		omsChargerChargeBillRecordDao.updateObject(omsChargerChargeBillRecord);
		String dzFun="&a=paycharge";
		//通知APP SERVER生成账单，账单生成后，如果是线上卡，则需要改写Offline_is_pay状态为4
//        requestURL = StringUtil.dzAppURL+dzFun+"&dianzhuanghao="+omsCharger.getQr_code()+"&user_pay_card="+userCard+"&start_em="+start_em+"&dianzhanid="+omsCharger.getStation_id()
//        		+"&end_em="+end_em+"&electric_charge="+this_amount_before+"&serve_charge="+char_bill+"&end_time="+StringUtil.now14time()+"&charge_time="+charge_time;
//        StringUtil.httpGetRequest(requestURL);		
        responseMsgHeader =data.substring(0, 34)+"55"+data.substring(36);
        json.setCode("200");
        json.setMsg("ok");
        json.setPojo(responseMsgHeader);
		return json;
	}
	public static void main(String[] args) throws ParseException {
//		BigDecimal min_1_decimal = BigDecimal.valueOf(1.0) ;
//		BigDecimal min_2_decimal = min_1_decimal.add(BigDecimal.valueOf(2.0));
//		BigDecimal min_3_decimal  =min_2_decimal.add(BigDecimal.valueOf(3.0));
//		System.out.println(min_3_decimal);
		
		String start_time ="20150122010203";
		String end_time   ="20150122192203";//20150122010203  20150124221213
		List<OmsChargerRate> omsChargerRateList = new ArrayList<OmsChargerRate>();
		OmsChargerRate OmsChargerRate_1 = new OmsChargerRate();
		OmsChargerRate_1.setStart_time(Time.valueOf("00:00:01"));
//		System.out.println(OmsChargerRate_1.getStart_time().getTime());
		OmsChargerRate_1.setEnd_time(Time.valueOf("06:00:00"));
		OmsChargerRate_1.setRate(BigDecimal.valueOf(0.01));
		omsChargerRateList.add(OmsChargerRate_1);
		OmsChargerRate OmsChargerRate_2 = new OmsChargerRate();
		OmsChargerRate_2.setStart_time(Time.valueOf("06:00:00"));
		OmsChargerRate_2.setEnd_time(Time.valueOf("11:59:59"));
		OmsChargerRate_2.setRate(BigDecimal.valueOf(0.02));
		omsChargerRateList.add(OmsChargerRate_2);
		OmsChargerRate OmsChargerRate_3 = new OmsChargerRate();
		OmsChargerRate_3.setStart_time(Time.valueOf("12:00:00"));
		OmsChargerRate_3.setEnd_time(Time.valueOf("17:59:59"));
		OmsChargerRate_3.setRate(BigDecimal.valueOf(0.03));
		omsChargerRateList.add(OmsChargerRate_3);
		OmsChargerRate OmsChargerRate_4 = new OmsChargerRate();
		OmsChargerRate_4.setStart_time(Time.valueOf("18:00:00"));
		OmsChargerRate_4.setEnd_time(Time.valueOf("23:59:59"));
		OmsChargerRate_4.setRate(BigDecimal.valueOf(0.04));
		omsChargerRateList.add(OmsChargerRate_4);
		float this_amount_before =  (float) 66.2;
		float result = StringUtil.calculateTotalPrice(start_time, end_time, omsChargerRateList, this_amount_before);
		System.out.println(result);
	}
	@SuppressWarnings("rawtypes")
	@Override
	public JsonCommon uploadChange(Map<String, String> map) {
//		String protocol_type = map.get("protocol_type");
		String protocol_version = map.get("protocol_version");
	
		switch(protocol_version){
		case "0101":
			json = uploadChange0101(map);
			break;
		case "0103":
			json = uploadChange0103(map);
			break;
		default:
			break;
		}
		return json; 

	}
	@SuppressWarnings("rawtypes")
	private JsonCommon uploadChange0101(Map<String, String> map) {
		JsonCommon json = new JsonCommon();
		String chargerId = map.get("chargerId");
		String status_value = map.get("status_value");
		String status_type= map.get("status_type");
		OmsCharger charger_query = new OmsCharger();
		charger_query.setCharger_id(chargerId);
		OmsCharger charger = omsChargerDao.findOneExample(charger_query, null, null);
		if(charger==null){
			json.setCode("10301201");
			json.setMsg("charger not found");
			return json;
		}
		OmsChargerStateAlternate alternateState_query =  new OmsChargerStateAlternate();
		alternateState_query.setCharger_id(chargerId);
		OmsChargerStateAlternate alternateState =  stateAlternateDao.findOneExample(alternateState_query,null,null);
		if(alternateState==null){
			json.setCode("10301201");
			json.setMsg("charger alternateState not found");
			return json;
		}	
		int status_value_int = Integer.valueOf(status_value);
		switch(status_type){//报文中01：充电状态02：故障状态03：预约状态04：充电插头连接状态  //数据库中0: 空闲;1: 预约;2 充电; 3 故障
		case "01":
			if(status_value_int==0){
				//alternateState.setCharge_status(0);
			}else{
				alternateState.setCharge_status(2);
			}
			stateAlternateDao.updateObject(alternateState);
			break;
		case "02":
			if(status_value_int==0){
				//alternateState.setCharge_status(0);
			}else{
				alternateState.setCharge_status(3);
			}
			stateAlternateDao.updateObject(alternateState);
			break;
		case "03":
			if(status_value_int==0){
				//alternateState.setCharge_status(0);
			}else{
				alternateState.setCharge_status(1);
			}
			stateAlternateDao.updateObject(alternateState);
			break;
		case "04":
			alternateState.setCable_status(status_value_int);
			stateAlternateDao.updateObject(alternateState);
			break;
		default:
			break;
		}
		json.setCode("200");
		json.setMsg("charger uploadChange0101 ok");
		return json;
	}
	@SuppressWarnings("rawtypes")
	private JsonCommon uploadChange0103(Map<String, String> map) {
		JsonCommon json = new JsonCommon();
		String chargerId = map.get("chargerId");
		String status_value = map.get("status_value");
		String status_type= map.get("status_type");
		OmsCharger charger_query = new OmsCharger();
		charger_query.setCharger_id(chargerId);
		List<OmsCharger> chargerList = omsChargerDao.findExample(charger_query, null, null, null, null);
		if(chargerList==null||chargerList.get(0).getCharger_type()==null){
			json.setCode("10301201");
			json.setMsg("charger not found");
			return json;
		}
		int chargerType = chargerList.get(0).getCharger_type();
		int port_no_int = 0;
		switch (chargerType) {//1--直流  2--交流  3--混合
		case 1:
			switch(status_type){
			case "01"://01：充电口使用状态
				port_no_int = Integer.valueOf(status_value.substring(7,8));
				OmsChargerStateDirect directState_query =  new OmsChargerStateDirect();
				directState_query.setCharger_id(chargerId);
				directState_query.setPort_no(port_no_int);
				OmsChargerStateDirect direct =  stateDirectDao.findOneExample(directState_query,null,null);
				switch(status_value.substring(4, 6)){//  数据库中   0: 空闲;1: 预约;2 充电; 3 故障
				case "00"://00：空闲
					direct.setCharge_status(0);
					break;
				case "01"://01：充电中
					direct.setCharge_status(2);
					break;
				case "02"://02：预约中
					direct.setCharge_status(1);
					break;
				default:
					break;
				}
				stateDirectDao.updateObject(direct);
				break;
			case "02"://02：故障状态
				json.setCode("103013 + 故障码："+status_value);
				switch(status_value){
				case "00FFFFFF"://系统错误
					json.setMsg("系统错误");
					break;
				case "00FFFF01"://解密错误
					json.setMsg("解密错误");
					break;
				case "00FF0001"://注册账号错误
					json.setMsg("注册账号错误");
					break;
				case "00FF0002"://注册密码错误
					json.setMsg("注册密码错误");
					break;
				case "00FF0003"://城市代码不合法
					json.setMsg("城市代码不合法");
					break;
				case "00FF0101"://注册设备地址重名
					json.setMsg("注册设备地址重名");
					break;
				case "00FF0102"://未知错误
					json.setMsg("未知错误");
					break;
				case "00FF0201"://命令执行失败
					json.setMsg("命令执行失败");
					break;
				case "00FF0202"://充电枪未插好
					json.setMsg("充电枪未插好");
					break;
				case "00FF0203"://急停按钮被按下，系统终止服务
					json.setMsg("急停按钮被按下，系统终止服务");
					break;
				case "00FF0204"://该用户卡号无权进行该操作
					json.setMsg("该用户卡号无权进行该操作");
					break;
				case "00FF0301"://报文帧码未定义
					json.setMsg("报文帧码未定义");
					break;
				case "00FF0302"://报文解析异常
					json.setMsg("报文解析异常");
					break;
				default://
					json.setMsg("未知错误");
					break;
				}
				OmsChargerStateDirect directState_query_1 =  new OmsChargerStateDirect();
				directState_query_1.setCharger_id(chargerId);
				List<OmsChargerStateDirect> directList =  stateDirectDao.findExample(directState_query_1,null,null,null,null);
				for(OmsChargerStateDirect direct_1 :directList){
					direct_1.setCharge_status(3);
					stateDirectDao.updateObject(direct_1);
				}
				break;
			case "03"://03：停车位状态
				break;
			default:
				break;
			}
			break;
		case 2:
			switch(status_type){
			case "01"://01：充电口使用状态
				port_no_int = Integer.valueOf(status_value.substring(7,8));
				OmsChargerStateAlternate alternateState_query =  new OmsChargerStateAlternate();
				alternateState_query.setCharger_id(chargerId);
				alternateState_query.setPort_no(port_no_int);
				OmsChargerStateAlternate alternate =  stateAlternateDao.findOneExample(alternateState_query,null,null);
				switch(status_value.substring(4, 6)){//  数据库中   0: 空闲;1: 预约;2 充电; 3 故障
				case "00"://00：空闲
					alternate.setCharge_status(0);
					break;
				case "01"://01：充电中
					alternate.setCharge_status(2);
					break;
				case "02"://02：预约中
					alternate.setCharge_status(1);
					break;
				default:
					break;
				}
				stateDirectDao.updateObject(alternate);
				break;
			case "02"://02：故障状态
				json.setCode("103013 + 故障码："+status_value);
				switch(status_value){
				case "00000000"://正常
					json.setMsg("正常");
					break;
				case "00000001"://其他故障
					json.setMsg("其他故障");
					break;
				case "00000002"://急停故障
					json.setMsg("急停故障");
					break;
				case "00000004"://电表故障
					json.setMsg("电表故障");
					break;
				case "00000008"://接触器故障
					json.setMsg("接触器故障");
					break;
				case "00000010"://读卡器故障
					json.setMsg("读卡器故障");
					break;
				case "内部过温故障"://内部过温故障
					json.setMsg("内部过温故障");
					break;
				case "00000040"://连接器故障
					json.setMsg("连接器故障");
					break;
				case "00000080"://绝缘故障
					json.setMsg("充电枪未插好");
					break;
				case "00000100"://输出电流异常
					json.setMsg("输出电流异常");
					break;
				case "00000200"://输出电压异常
					json.setMsg("输出电压异常");
					break;
				case "00000400"://充电机模块故障
					json.setMsg("充电机模块故障");
					break;
				case "00000800"://充电机通信故障
					json.setMsg("充电机通信故障");
					break;
				case "00001000"://BMS禁止充电
					json.setMsg("BMS禁止充电");
					break;
				case "00002000"://输入电压异常
					json.setMsg("输入电压异常");
					break;
				default://
					json.setMsg("未知故障");
					break;
				}
				OmsChargerStateAlternate alternateState_query_1 =  new OmsChargerStateAlternate();
				alternateState_query_1.setCharger_id(chargerId);
				List<OmsChargerStateAlternate> alternateList =  stateAlternateDao.findExample(alternateState_query_1,null,null,null,null);
				for(OmsChargerStateAlternate alternate_1 :alternateList){
					alternate_1.setCharge_status(3);
					stateAlternateDao.updateObject(alternate_1);
				}
				OmsChargerErrorRecord omsChargerErrorRecord = new OmsChargerErrorRecord();
				omsChargerErrorRecord.setCharger_id(chargerId);
				omsChargerErrorRecord.setError_code(status_value);
				omsChargerErrorRecord.setError_msg(json.getMsg());
				omsChargerErrorRecord.setStatus(0);//未处理
				omsChargerErrorRecord.setValid_flag(1);
				omsChargerErrorRecord.setCreate_oper_id("000");//表示系统直接上传
				omsChargerErrorRecord.setCreate_time(new Date());
				omsChargerErrorRecordDao.save(omsChargerErrorRecord);
				break;
			case "03"://03：停车位状态
				break;
			default:
				break;
			}
			break;	
		default:	
			break;	
		}
		return json;
	}
	@Override
	public Map<String, String> ev3c2uploadHeart(Map<String, String> map) {
		return null;
	}
	@Override
	public Map<String, String> ev3c2uploadBill(Map<String, String> map) throws Exception{

		String userCard =map.get("user_pay_card");
		UploadBillProcess uploadBillProcess = BillProcessFactory.getBillProcessInstance(userCard);
		if(uploadBillProcess != null)
			map = uploadBillProcess.ProcessBill(map);

		// 如果是线下充值卡，就 1 数据库做记录，2  不传单价给订单服务器，调用订单接口 3 返回json
//		if(userCard.startsWith("18806")){
//			UploadBillProcess uploadBillProcess = BillProcessFactory.getBillProcessInstance(userCard);
//			map.put("cardType", CardType.OFFLINE_CARD.value());
////			map = ev3c2uploadBill18806(map);
//			map = uploadBillProcess.ProcessBill(map);
//		}
		// 如果是线下卡（身份认证卡） ,则1 先查询数据库：  如果桩允许生成费用，则 2 数据库做记录；查询相关费率传总价给订单服务器，调用订单接口 3 返回json； 
		//如果桩不允许生成费用，则 查询单价 ，2 直接传总价给订单服务器，调用订单接口 ；数据库做记录3 返回json
//		if(userCard.startsWith("18805")){
//			map.put("cardType", CardType.IDENTITY_CARD.value());
//			map = ev3c2uploadBill18805(map);
//		}
		// 如果是线上卡app用户，,则1 先查询数据库：  如果桩允许生成费用，则 2 数据库做记录；查询相关费率传总价给订单服务器，调用订单接口 3 返回json； 
		//如果桩不允许生成费用，则 查询单价 ，2 直接传总价给订单服务器，调用订单接口 ；数据库做记录3 返回json
//		if(userCard.startsWith("18808")&&!userCard.substring(0, 9).equals("188089999")){
//			map.put("cardType", CardType.ONLINE_CARD.value());
//			map = ev3c2uploadBill188089999(map);
//		}
		// 如果是线上卡企业用户，,则1 先查询数据库：  如果桩允许生成费用，则 2 数据库做记录；查询相关费率传总价给订单服务器，调用订单接口 3 返回json； 
		//如果桩不允许生成费用，则 查询单价 ，2 直接传总价给订单服务器，调用订单接口 ；数据库做记录3 返回json
//		if(userCard.startsWith("18808")){
//			map.put("cardType", CardType.ONLINE_CARD.value());
//			map = ev3c2uploadBill18808(map);
//		}
		return map;
	}
	private Map<String, String> ev3c2uploadBill18808(Map<String, String> map) throws ParseException, OmsDaoException{
		return  ev3c2uploadBill18805(map);
	}
	private Map<String, String> ev3c2uploadBill188089999 (Map<String, String> map) throws ParseException, OmsDaoException{
		return  ev3c2uploadBill18805(map);
	}

	private Map<String, String> ev3c2uploadBill18805(Map<String, String> map) throws ParseException, OmsDaoException {
		String data,chargerId,responseMsgHeader,requestURL; 
		chargerId = map.get("chargerId");
		OmsCharger omsCharger_query = new OmsCharger();
		OmsCharger omsCharger =omsChargerDao.findOneExample(omsCharger_query, null, null);
		if(omsCharger==null){
			map.put("msgResponseCode",OmsConstant.MsgResponseCodeEnum.ChargerIdVaildNotFound.value());
			return map;
		}
		OmsStation omsStationQuery = new OmsStation(omsCharger.getStation_id());
		OmsStation omsStation = omsStationDao.findRecordByPK(omsStationQuery);
		String start_time = map.get("start_time");
		Date start_time_date = StringUtil.StrToDate(start_time);
		String end_time = map.get("end_time");
		Date end_time_date = StringUtil.StrToDate(end_time);
		String userCard = map.get("userCard");
		float start_em = StringUtil.Str2float(map.get("start_em")); //*充电前电表读数 BIN码 4 系数为0.01 低字节在前，高字节在后，实际值X100上送
		float end_em =  StringUtil.Str2float(map.get("end_em")); //*充电后电表读数 BIN码 4 系数为0.01 低字节在前，高字节在后，实际值X100上送
		float this_reading = StringUtil.Str2float(map.get("this_reading"));//*本次充电电量  与上类似
		float this_amount_before =  StringUtil.Str2float(map.get("this_amount_before"));//*本次充电金额  与上类似
		float offline_balance_start =  StringUtil.Str2float(map.get("offline_balance_start"));//充电前卡余额  与上类似
		float offline_balance_end =  StringUtil.Str2float(map.get("offline_balance_end"));//充电后卡余额  与上类似
		float service_payment =  StringUtil.Str2float(map.get("service_payment"));//服务费金额  2   与上类似
		String protocol_version = map.get("protocol_version");
		String oms_msg_charge_jrnl = map.get("oms_msg_charge_jrnl");//之前充电的流水号
		String offline_is_pay =  map.get("offline_is_pay");//是否线下支付
		int offline_is_pay_int = Integer.valueOf(offline_is_pay,2);
//		String charge_end_reason =data.substring(166, 168);//2.0协议中报文体中没有这个字段，暂时不存
//          充电结束原因
//			0x01: 后台远程控制正常结束
//			0x02: 本地刷卡控制正常结束
//			0x03: 满足预设停止条件正常结束
//			0x04：电池满电正常结束
		String start_type =  map.get("start_type");//充电启动方式   0x00 服务器开启 0x01 刷卡开启
		String vin = map.get("vin");//车辆识别码
		OmsChargerChargeBillRecord  omsChargerChargeBillRecord_query  = new OmsChargerChargeBillRecord(); 
		omsChargerChargeBillRecord_query.setCharge_jrnl(oms_msg_charge_jrnl);
		OmsChargerChargeBillRecord  omsChargerChargeBillRecord = omsChargerChargeBillRecordDao.findOneExample(omsChargerChargeBillRecord_query, "create_time", "desc");
		if(omsChargerChargeBillRecord==null){
//			json.setCode("10301201");
//			json.setMsg("charge bill record not found!");
			map.put("msgResponseCode",OmsConstant.MsgResponseCodeEnum.SerialNoNotFound.value());
			return map;
		}		
		//查询卡号是不是在白名单里面。
		OmsChargerOfflineWhitelist whitelist_query = new OmsChargerOfflineWhitelist();
		whitelist_query.setCharger_id(chargerId);
		whitelist_query.setUser_pay_card(userCard);
		OmsChargerOfflineWhitelist whitelist = omsChargerOfflineWhitelistDao.findOneExample(whitelist_query, null, null);
		if(whitelist!=null){
			service_payment = 0;
			this_amount_before = 0;
		}
		omsChargerChargeBillRecord.setEnd_time(end_time_date);
		omsChargerChargeBillRecord.setStart_time(start_time_date);
		omsChargerChargeBillRecord.setStart_em(String.valueOf(start_em));
		omsChargerChargeBillRecord.setEnd_em(String.valueOf(end_em));
		omsChargerChargeBillRecord.setThis_reading(String.valueOf(this_reading));
		omsChargerChargeBillRecord.setThis_amount_before(this_amount_before);
		omsChargerChargeBillRecord.setThis_amount(this_amount_before);
		omsChargerChargeBillRecord.setChar_bill(service_payment);
		omsChargerChargeBillRecord.setOffline_balance_start(String.valueOf(offline_balance_start));
		omsChargerChargeBillRecord.setOffline_balance_end(String.valueOf(offline_balance_end));
		omsChargerChargeBillRecord.setStatus(5);
		omsChargerChargeBillRecord.setValid_flag(1);
//		omsChargerChargeBillRecord.setCharge_start_mode(charge_start_mode);
		omsChargerChargeBillRecord.setChar_bill(service_payment);
//		omsChargerChargeBillRecord.setCharge_end_reason(charge_end_reason);
//		omsChargerChargeBillRecord.setControl_type(control_type);
//		omsChargerChargeBillRecord.setOpen_restricted_data(String.valueOf(open_restricted_data_float));
		omsChargerChargeBillRecord.setVIN(vin);
		omsChargerChargeBillRecord.setUser_pay_card(userCard);
		List<OrderBaseData> orderBaseDatas = new ArrayList<OrderBaseData>();
		//订单服务器下单
		//1 先查询数据库：  如果桩允许生成费用，则 2 数据库做记录；查询相关费率传总价给订单服务器，调用订单接口 3 返回json； 
		//如果桩不允许生成费用，则 查询单价 ，2 直接传总价给订单服务器，调用订单接口 ；数据库做记录3 返回json
		//通过桩查询服务费单价 TODO  oms_charger_rate[电桩费率表]  start_time  end_time
		float charge_fee_totalPrice = 0;
		float service_fee_totalPrice = 0;
		if(omsCharger.getIs_allow_generate_fee()==1){
			//电费
			int charge_fee_rate_schema = omsCharger.getRate_schema_charge_fee();
			OmsChargerRate omsChargerRate_query = new OmsChargerRate();
			omsChargerRate_query.setRate_schema(charge_fee_rate_schema);
			List<OmsChargerRate> omsChargerRateList =  chargerRateService.findExample(omsChargerRate_query);
			if(omsChargerRateList.size()>0){
				if(omsChargerRateList.get(0).getCharge_mode() == 0){
					charge_fee_totalPrice = StringUtil.calculateTotalPrice(start_time,end_time,omsChargerRateList,this_amount_before);
				}else{
					charge_fee_totalPrice = omsChargerRateList.get(0).getRate().floatValue();
				}
			}else{
				charge_fee_totalPrice = 0;
			}
			//服务费
			int service_fee_rate_schema = omsCharger.getRate_schema_charge_fee();
			OmsChargerRate omsChargerRate_query_service = new OmsChargerRate();
			omsChargerRate_query.setRate_schema(service_fee_rate_schema);
			List<OmsChargerRate> omsChargerRateServiceList =  chargerRateService.findExample(omsChargerRate_query_service);
			if(omsChargerRateServiceList.size()>0){
				if(omsChargerRateServiceList.get(0).getCharge_mode() == 0){
					service_fee_totalPrice = StringUtil.calculateTotalPrice(start_time,end_time,omsChargerRateList,this_amount_before);
				}else{
					service_fee_totalPrice = omsChargerRateServiceList.get(0).getRate().floatValue();
				}
			}else{
				service_fee_totalPrice = 0;
			}
		}else{
			charge_fee_totalPrice = this_amount_before;
		}
		charge_fee_totalPrice = (float)(Math.round(charge_fee_totalPrice*100)/100);
		service_fee_totalPrice = (float)(Math.round(service_fee_totalPrice*100)/100);
		//ChargeService("100001", "充电服务"),
		//CollectingElectricityFee("100002", "代收电费服务"),
		OrderBaseData orderBaseData_ChargeService = new OrderBaseData();
		if(userCard.startsWith("18808")&&!userCard.substring(0, 9).equals("188089999")){
			orderBaseData_ChargeService.setAppId(BizSystemCode.DzApp.value());
		}
		orderBaseData_ChargeService.setBuyNum(BigDecimal.valueOf(this_reading));
		orderBaseData_ChargeService.setCardNo(userCard);
		orderBaseData_ChargeService.setCardType(map.get("cardType"));
		orderBaseData_ChargeService.setStartTime(omsChargerChargeBillRecord.getStart_time());
		orderBaseData_ChargeService.setEndTime(omsChargerChargeBillRecord.getEnd_time());
		orderBaseData_ChargeService.setEquipmentNo(chargerId);
		if(omsStation!=null){
			orderBaseData_ChargeService.setPlantName(omsStation.getStation_name());
		}		
		orderBaseData_ChargeService.setPlantId(omsCharger.getStation_id());
		orderBaseData_ChargeService.setServiceNo(OrderServiceEnum.ChargeService.value());
		orderBaseData_ChargeService.setServiceProviderCode(omsCharger.getOper_merchant_id());
		orderBaseData_ChargeService.setUnitPrice(null);
		orderBaseData_ChargeService.setAuxEquipmentNo("0");
		orderBaseData_ChargeService.setTotalPrice(BigDecimal.valueOf(service_fee_totalPrice));
		//OS的分成类
		DivideInfo divideInfo = new DivideInfo();
		OmsServiceSplitratio serviceSplitratio_query = new OmsServiceSplitratio();
		serviceSplitratio_query.setCharger_id(chargerId);
//				OmsServiceSplitratio serviceSplitratio = serviceSplitratioDaoImpl.
		String condition =" where scheme_no in (select scheme_no from oms_service_splitratio "
				+ "where service_no ='"+ OrderServiceEnum.CollectingElectricityFee.value() +"' and charger_id = '"+ chargerId +"')";
		List<OmsSplitratioScheme> list_omsServiceSplitratio = omsSplitratioSchemeDao.findListByCondition(
				new OmsServiceSplitratio(),condition);
		divideInfo.setKeyLink(chargerId);
		divideInfo.setPlantId(omsCharger.getStation_id());
		StringBuilder merchantCodes_sb = new StringBuilder("");
		StringBuilder ratios_sb = new StringBuilder("");
		StringBuilder minAmount_sb = new StringBuilder("");
		if(list_omsServiceSplitratio.size()>0){
			for(OmsSplitratioScheme scheme : list_omsServiceSplitratio){
				merchantCodes_sb.append(scheme.getEntity_id()+",");
				ratios_sb.append(scheme.getRatios()+",");
				minAmount_sb.append(scheme.getMin_amount()+",");
			}
			merchantCodes_sb.deleteCharAt(merchantCodes_sb.length() -1 );
			ratios_sb.deleteCharAt(ratios_sb.length() -1 );
			minAmount_sb.deleteCharAt(minAmount_sb.length() -1 );
			divideInfo.setMerchantCodes(merchantCodes_sb.toString());
			divideInfo.setRatios(ratios_sb.toString());
			divideInfo.setMinAmount(minAmount_sb.toString());
			orderBaseData_ChargeService.setDivideInfo(divideInfo);
		}
		//线上卡oms_pub_whitelist[白名单表] 不做
//				orderBaseData.setWhiteListInfo("");
		
//				orderBaseData.setDivideInfo("");
		OrderBaseData orderBaseData_Chargefee = new OrderBaseData();
		if(userCard.startsWith("18808")&&!userCard.substring(0, 9).equals("188089999")){
			orderBaseData_Chargefee.setAppId(BizSystemCode.DzApp.value());
		}
		orderBaseData_Chargefee.setBuyNum(BigDecimal.valueOf(this_reading));
		orderBaseData_Chargefee.setCardNo(userCard);
		orderBaseData_Chargefee.setCardType(map.get("cardType"));
		orderBaseData_Chargefee.setStartTime(omsChargerChargeBillRecord.getStart_time());
		orderBaseData_Chargefee.setEndTime(omsChargerChargeBillRecord.getEnd_time());
		orderBaseData_Chargefee.setEquipmentNo(chargerId);
//				orderBaseData_ChargeService.setMerchantCode(omsCharger.getOper_merchant_id());
		if(omsStation!=null){
			orderBaseData_Chargefee.setPlantName(omsStation.getStation_name());
		}		
		orderBaseData_Chargefee.setPlantId(omsCharger.getStation_id());
		orderBaseData_Chargefee.setServiceNo(OrderServiceEnum.CollectingElectricityFee.value());
		orderBaseData_Chargefee.setServiceProviderCode(omsCharger.getOper_merchant_id());
		orderBaseData_Chargefee.setTotalPrice(BigDecimal.valueOf(charge_fee_totalPrice));
		orderBaseData_Chargefee.setAuxEquipmentNo("0");
		//暂时不做白名单  oms_pub_whitelist[白名单表]
//				orderBaseData_Chargefee.setWhiteListInfo("");
//				orderBaseData_Chargefee.setDivideInfo("");
		orderBaseDatas.add(orderBaseData_ChargeService);
		orderBaseDatas.add(orderBaseData_Chargefee);
		//TODO 测试时屏蔽，正式时打开
//		RetVO retVO = orderRpcClient.createOrder(orderBaseDatas);
//		if(retVO==null||!retVO.getRetCode().equals(retVO.SuccessCode)){
//			json.setCode(retVO.FailCode);
//		    json.setMsg("createOrder fail");
//		    responseMsgHeader =data.substring(0, 34)+"55"+data.substring(36);
//		    json.setPojo(responseMsgHeader);
//		    return json;
//		}
//    	String bizData = (String) retVO.getBizData();
//    	CreatedOrderVO createdOrderVO = JSON.parseObject(bizData, CreatedOrderVO.class);
//		omsChargerChargeBillRecord.setThis_amount(Float.valueOf(createdOrderVO.getTotalFee().toString()));
		omsChargerChargeBillRecord.setStatus(5);//omsChargerChargeBillRecord
		/*
		 * 0 开启充电：已下发指令未回复；
			1 充电中 ：已确认桩回复；
			2 电充满未结束：如未拔枪则是此状态； 
			3 关闭充电：已下发指令 ；
			4 充电结束 ：桩回复充电结束 ；
			5 已生成账单；
			6 已结算 ；
			7 已退款 ；
			8 充电失败。
		 * */
		omsChargerChargeBillRecordDao.updateObject(omsChargerChargeBillRecord);
//		String dzFun="&a=paycharge";
		//通知APP SERVER生成账单，账单生成后，如果是线上卡，则需要改写Offline_is_pay状态为4
//        requestURL = StringUtil.dzAppURL+dzFun+"&dianzhuanghao="+omsCharger.getQr_code()+"&user_pay_card="+userCard+"&start_em="+start_em+"&dianzhanid="+omsCharger.getStation_id()
//        		+"&end_em="+end_em+"&electric_charge="+this_amount_before+"&serve_charge="+char_bill+"&end_time="+now+"&charge_time="+charge_time;
//        StringUtil.httpGetRequest(requestURL);		
//        responseMsgHeader =data.substring(0, 34)+"55"+data.substring(36);
//        json.setCode("200");
//        json.setMsg("ok");
//        json.setPojo(responseMsgHeader);
		return map;			
	
	}

	/*
	private Map<String, String> ev3c2uploadBill18806(Map<String, String> map) {
		//如果是线下充值卡，就 1 数据库做记录，2  不传单价给订单服务器，调用订单接口 3 返回json
		String chargerId,responseMsgHeader,requestURL; 
		chargerId = map.get("chargerId");
		OmsCharger omsCharger_query = new OmsCharger();
		omsCharger_query.setCharger_id(chargerId);
		OmsCharger omsCharger =omsChargerDao.findOneExample(omsCharger_query, null, null);
		if(omsCharger==null){
			map.put("msgResponseCode",OmsConstant.MsgResponseCodeEnum.ChargerIdVaildNotFound.value());
			return map;
		}
		String start_time =  map.get("start_time");
		Date start_time_date =StringUtil.StrToDate(start_time);
		String end_time =  map.get("end_time");
		Date end_time_date =StringUtil.StrToDate(end_time);
		String user_pay_card = map.get("user_pay_card");  
		float start_em = StringUtil.Str2float(map.get("start_em")); //*充电前电表读数 BIN码 4 系数为0.01 低字节在前，高字节在后，实际值X100上送
		float end_em =  StringUtil.Str2float(map.get("end_em")); //*充电后电表读数 BIN码 4 系数为0.01 低字节在前，高字节在后，实际值X100上送
		float this_reading = StringUtil.Str2float(map.get("this_reading"));//*本次充电电量  与上类似
		float this_amount_before =  StringUtil.Str2float(map.get("charge_payment"));//*本次充电金额  与上类似
		//float offline_balance_start =  StringUtil.Str2float(map.get("offline_balance_start"));//充电前卡余额  与上类似
		float offline_balance_end =  StringUtil.Str2float(map.get("offline_balance_end"));//充电后卡余额  与上类似
		float service_payment =  StringUtil.Str2float(map.get("service_payment"));//服务费金额  2   与上类似
		String protocol_version = map.get("protocol_version");
		String oms_msg_charge_jrnl = map.get("oms_msg_charge_jrnl");//之前充电的流水号
		String offline_is_pay =  map.get("offline_is_pay");//是否线下支付
		int offline_is_pay_int = Integer.valueOf(offline_is_pay,2);
//		String charge_end_reason =data.substring(166, 168);//2.0协议中报文体中没有这个字段，暂时不存
//          充电结束原因
//			0x01: 后台远程控制正常结束
//			0x02: 本地刷卡控制正常结束
//			0x03: 满足预设停止条件正常结束
//			0x04：电池满电正常结束
		String start_type =  map.get("start_type");//充电启动方式   0x00 服务器开启 0x01 刷卡开启
		String vin = map.get("vin");//车辆识别码
		OmsChargerChargeBillRecord  omsChargerChargeBillRecord_query  = new OmsChargerChargeBillRecord(); 
		omsChargerChargeBillRecord_query.setCharge_jrnl(oms_msg_charge_jrnl);
		omsChargerChargeBillRecord_query.setCharger_id(chargerId);
		OmsChargerChargeBillRecord  omsChargerChargeBillRecord = omsChargerChargeBillRecordDao.findOneExample(omsChargerChargeBillRecord_query, "create_time", "desc");
		if(omsChargerChargeBillRecord==null){
			json.setCode("10301201");
			json.setMsg("charge bill record org_serial_no not found!");
			log.error("Bill record not found");
			map.put("msgResponseCode",OmsConstant.MsgResponseCodeEnum.SerialNoNotFound.value());
			return map;
		}
		//查询卡号是不是在白名单里面。
		OmsChargerOfflineWhitelist whitelist_query = new OmsChargerOfflineWhitelist();
		whitelist_query.setCharger_id(chargerId);
		whitelist_query.setUser_pay_card(user_pay_card);
		OmsChargerOfflineWhitelist whitelist = omsChargerOfflineWhitelistDao.findOneExample(whitelist_query, null, null);
		if(whitelist!=null){
			service_payment = 0;
			this_amount_before = 0;
		}
		Date now = new Date();
		omsChargerChargeBillRecord.setEnd_time(end_time_date);
		omsChargerChargeBillRecord.setStart_time(start_time_date);
		
		//long charge_time = now.getTime() - omsChargerChargeBillRecord.getStart_time().getTime();
		omsChargerChargeBillRecord.setStart_em(String.valueOf(start_em));
		omsChargerChargeBillRecord.setEnd_em(String.valueOf(end_em));
		omsChargerChargeBillRecord.setThis_reading(String.valueOf(this_reading));
		omsChargerChargeBillRecord.setThis_amount_before(this_amount_before);
		omsChargerChargeBillRecord.setThis_amount(this_amount_before);
		omsChargerChargeBillRecord.setChar_bill(service_payment);
//		omsChargerChargeBillRecord.setOffline_balance_start(String.valueOf(offline_balance_start));
		omsChargerChargeBillRecord.setOffline_balance_end(String.valueOf(offline_balance_end));
		omsChargerChargeBillRecord.setStatus(OmsConstant.ChargingBillStatus.BillGenerated);
		omsChargerChargeBillRecord.setValid_flag(1);
		omsChargerChargeBillRecord.setCharge_start_mode(start_type);
		omsChargerChargeBillRecord.setChar_bill(service_payment);
//		omsChargerChargeBillRecord.setCharge_end_reason(charge_end_reason);
//		omsChargerChargeBillRecord.setControl_type(control_type);
//		omsChargerChargeBillRecord.setOpen_restricted_data(open_restricted_data);
//		omsChargerChargeBillRecord.setVIN(vehicle_identification_code);
		omsChargerChargeBillRecord.setUser_pay_card(user_pay_card);
		//订单服务器下单
		List<OrderBaseData> orderBaseDatas = new ArrayList<>();
		//ChargeService("100001", "充电服务"),
		//CollectingElectricityFee("100002", "代收电费服务"),
		OrderBaseData orderBaseData_ChargeService = new OrderBaseData();
//		if(user_pay_card.startsWith("18808")&&!user_pay_card.substring(0, 9).equals("188089999")){
		orderBaseData_ChargeService.setAppId(BizSystemCode.DzApp.value());
//		}
//		orderBaseData.setAppId("");
//		orderBaseData.setAuxEquipmentNo("");
		orderBaseData_ChargeService.setBuyNum(BigDecimal.valueOf(this_reading));
		orderBaseData_ChargeService.setCardNo(user_pay_card);
		orderBaseData_ChargeService.setCardType(map.get("cardType"));
		orderBaseData_ChargeService.setStartTime(omsChargerChargeBillRecord.getStart_time());
		orderBaseData_ChargeService.setEndTime(omsChargerChargeBillRecord.getEnd_time());
		orderBaseData_ChargeService.setEquipmentNo(chargerId);
		orderBaseData_ChargeService.setMerchantCode(omsCharger.getOper_merchant_id());
		orderBaseData_ChargeService.setPlantId(omsCharger.getStation_id());
		orderBaseData_ChargeService.setServiceNo(OrderServiceEnum.ChargeService.value());
		orderBaseData_ChargeService.setServiceProviderCode(omsCharger.getOper_merchant_id());
		orderBaseData_ChargeService.setTotalPrice(BigDecimal.valueOf(service_payment));
		orderBaseData_ChargeService.setAuxEquipmentNo("0");
		orderBaseData_ChargeService.setPayerBalance("0");
//		orderBaseData_ChargeService.setUnitPrice("");
//		orderBaseData_ChargeService.setUserId("");
//		orderBaseData_ChargeService.setUserType("");

		//2.0 不做打折白名单
//		orderBaseData_ChargeService.setWhiteListInfo("");
		//OS的分成类
		DivideInfo divideInfo = new DivideInfo();
		OmsServiceSplitratio serviceSplitratio_query = new OmsServiceSplitratio();
		serviceSplitratio_query.setCharger_id(chargerId);
		//		OmsServiceSplitratio serviceSplitratio = serviceSplitratioDaoImpl.
		String condition = " where scheme_no in (select scheme_no from oms_service_splitratio where service_no ='" + OrderServiceEnum.ChargeService.value() + "' and charger_id = '" + chargerId + "')";
		List<OmsSplitratioScheme> list_omsServiceSplitratio = omsSplitratioSchemeDao.findListByCondition(new OmsSplitratioScheme(), condition);
		divideInfo.setKeyLink(chargerId);
		divideInfo.setPlantId(omsCharger.getStation_id());
		StringBuilder merchantCodes_sb = new StringBuilder("");
		StringBuilder ratios_sb = new StringBuilder("");
		StringBuilder minAmount_sb = new StringBuilder("");
		if (list_omsServiceSplitratio.size() > 0)
		{
			for (OmsSplitratioScheme scheme : list_omsServiceSplitratio)
			{
				merchantCodes_sb.append(scheme.getEntity_id() + ",");
				ratios_sb.append(scheme.getRatios() + ",");
				minAmount_sb.append(scheme.getMin_amount() + ",");
			}
			merchantCodes_sb.deleteCharAt(merchantCodes_sb.length() - 1);
			ratios_sb.deleteCharAt(ratios_sb.length() - 1);
			minAmount_sb.deleteCharAt(minAmount_sb.length() - 1);
			divideInfo.setMerchantCodes(merchantCodes_sb.toString());
			divideInfo.setRatios(ratios_sb.toString());
			divideInfo.setMinAmount(minAmount_sb.toString());
			//divideInfo.setMerchantCodes();
			orderBaseData_ChargeService.setDivideInfo(divideInfo);
		}


		OrderBaseData orderBaseData_Electricfee = new OrderBaseData();
//		if(user_pay_card.startsWith("18808")&&!user_pay_card.substring(0, 9).equals("188089999")){
		orderBaseData_Electricfee.setAppId(BizSystemCode.DzApp.value());
//		}
//		orderBaseData.setAppId("");
//		orderBaseData.setAuxEquipmentNo("");
		orderBaseData_Electricfee.setBuyNum(BigDecimal.valueOf(this_reading));
		orderBaseData_Electricfee.setCardNo(user_pay_card);
		orderBaseData_Electricfee.setCardType(map.get("cardType"));
		orderBaseData_Electricfee.setStartTime(omsChargerChargeBillRecord.getStart_time());
		orderBaseData_Electricfee.setEndTime(omsChargerChargeBillRecord.getEnd_time());
		orderBaseData_Electricfee.setEquipmentNo(chargerId);
		orderBaseData_Electricfee.setMerchantCode(omsCharger.getOper_merchant_id());
		orderBaseData_Electricfee.setPlantId(omsCharger.getStation_id());
		orderBaseData_Electricfee.setServiceNo(OrderServiceEnum.CollectingElectricityFee.value());
		orderBaseData_Electricfee.setServiceProviderCode(omsCharger.getOper_merchant_id());
		orderBaseData_Electricfee.setTotalPrice(BigDecimal.valueOf(this_amount_before));
		orderBaseData_Electricfee.setAuxEquipmentNo("0");
		orderBaseData_ChargeService.setPayerBalance("0");
		//		orderBaseData_Chargefee.setUnitPrice("");
//		orderBaseData_Chargefee.setUserId("");
//		orderBaseData_Chargefee.setUserType("");
//		orderBaseData_Electricfee.setDivideInfo(divideInfo);
		
		
		orderBaseDatas.add(orderBaseData_ChargeService);
		orderBaseDatas.add(orderBaseData_Electricfee);
		//TODO 测试时屏蔽，正式时打开
		try
		{
			RetVO retVO = orderRpcClient.createOrder(orderBaseDatas);
			if (retVO == null || !retVO.getRetCode().equals(RetVO.SuccessCode))
			{
				//			json.setCode(retVO.FailCode);
				//			json.setMsg("createOrder fail");
				//			responseMsgHeader = data.substring(0, 34) + "55" + data.substring(36);
				//			json.setPojo(responseMsgHeader);
				log.debug("error on calling order server");
				map.put("msgResponseCode", OmsConstant.MsgResponseCodeEnum.SysError.value());
				return map;
				//		    return json;
			}
//			String bizData = retVO.getBizData().toString();
//			log.debug(bizData);
			//TODO luoyp, waiting for Zhou Tian to fix the create order interface, so that we can get the order no after calling the interface
//			CreateOrderReturnVO.CreatedOrderVO createdOrderVO = retVO.getBizData();
			String bizData = retVO.getBizData().toString();
			log.debug(bizData);
			RetVO.CreatedOrderVO createdOrderVO = JSON.parseObject(bizData, RetVO.CreatedOrderVO.class);
			omsChargerChargeBillRecord.setThis_amount(Float.valueOf(createdOrderVO.getTotalFee().toString()));
			omsChargerChargeBillRecord.setOrder_no(createdOrderVO.getOrderNo());
			omsChargerChargeBillRecordDao.updateObject(omsChargerChargeBillRecord);
			//		String dzFun="&a=paycharge";
			//通知APP SERVER生成账单，账单生成后，如果是线上卡，则需要改写Offline_is_pay状态为4
			//        requestURL = StringUtil.dzAppURL+dzFun+"&dianzhuanghao="+omsCharger.getQr_code()+"&user_pay_card="+userCard+"&start_em="+start_em+"&dianzhanid="+omsCharger.getStation_id()
			//        		+"&end_em="+end_em+"&electric_charge="+this_amount_before+"&serve_charge="+char_bill+"&end_time="+StringUtil.now14time()+"&charge_time="+charge_time;
			//        StringUtil.httpGetRequest(requestURL);
			//        responseMsgHeader =data.substring(0, 34)+"55"+data.substring(36);
			json.setCode("200");
			json.setMsg("ok");
			map.put("msgResponseCode", OmsConstant.MsgResponseCodeEnum.Normal.value());
			//        json.setPojo(responseMsgHeader);
			return map;
		}
		catch (Exception e)
		{
			log.error(e.getMessage(), e);
			throw e;
		}
	
	}
	*/

	@Override
	public String ev3c2uploadChange(ChargerSendingMsgHeader header, String data) throws BizException
	{
		log.info(header);
		log.info(data);
		String chargerId = header.getChargerId();
		String chargerType = header.getChargerType();
		String portNo = header.getPortNo();
		Date now = new Date();

		StateChangeBody stateChangeBody = MessageAnalysisHelper.analyse(data, StateChangeBody.class);
		log.debug(stateChangeBody);

		if(!stateChangeBody.isStateTypeValid())
			throw new BizException("invalid state change type " + stateChangeBody.getStateType());

		String reply_code = OmsConstant.MsgResponseCodeEnum.Normal.value();
		String body = "";
		log.debug(reply_code);

		switch (stateChangeBody.getStateType())
		{
			case "01":                                             //空闭（0x01）
				if(OmsConstant.ChargerType.AC.equals(chargerType))
				{
					stateAlternateDao.exec(MessageFormat.format("update oms_charger_state_alternate set online_status = 1 ,charge_status =  {0} where charger_id = ''{1}'' and port_no = {2} ",
							OmsConstant.ChargerPortStatus.Available, chargerId, portNo));
				}
				else if(OmsConstant.ChargerType.DC.equals(chargerType))
				{

					stateDirectDao.exec(MessageFormat.format("update oms_charger_state_direct       set online_status = 1 ,charge_status =  {0} where charger_id = ''{1}'' and port_no = {2} ",
							OmsConstant.ChargerPortStatus.Available, chargerId, portNo));
				}
				break;
			case "02":                            //预约（0x02）
			/* ---不允许线下预约---*/
				break;
			case "03":                                             //开启充电（0x03）
				boolean validstatus_charging = false;
				if(OmsConstant.ChargerType.AC.equals(chargerType))
				{
					OmsChargerStateAlternate ac_port =  stateAlternateDao.findOneExampleByCondition(new OmsChargerStateAlternate(), MessageFormat.format("where charger_id = ''{0}'' and port_no = {1} ", chargerId, portNo));
					if(OmsConstant.ChargerPortStatus.Charging != ac_port.getCharge_status())
					{
						stateAlternateDao.exec(MessageFormat
								.format("update oms_charger_state_alternate set online_status = 1 ,charge_status =  {0} where charger_id = ''{1}'' and port_no = {2} ", OmsConstant.ChargerPortStatus.Charging, chargerId,
										portNo));
						validstatus_charging = true;
					}
				}
				else if(OmsConstant.ChargerType.DC.equals(chargerType))
				{
					OmsChargerStateDirect dc_port =  stateDirectDao.findOneExampleByCondition(new OmsChargerStateDirect(), MessageFormat.format("where charger_id = ''{0}'' and port_no = {1} ", chargerId, portNo));
					if(OmsConstant.ChargerPortStatus.Charging != dc_port.getCharge_status())
					{
						stateDirectDao.exec(MessageFormat
								.format("update oms_charger_state_direct       set online_status = 1 ,charge_status =  {0} where charger_id = ''{1}'' and port_no = {2} ", OmsConstant.ChargerPortStatus.Charging, chargerId,
										portNo));
						validstatus_charging = true;
					}
				}
				if(!validstatus_charging)
				{
					reply_code = OmsConstant.MsgResponseCodeEnum.SysError.value();
					break;
				}
				else
				{
					ChargingStateBody stateBody = MessageAnalysisHelper.analyse(data, ChargingStateBody.class);
					OmsChargerChargeBillRecord charging_bill = new OmsChargerChargeBillRecord();
					charging_bill.setCharge_jrnl(chargerId + String.format("%02d", Integer.valueOf(portNo)) + serialGenerater.generateSerialNo());
					charging_bill.setMsg_charge_jrnl(header.getChargerSerialNo());
					charging_bill.setCharger_id(chargerId);
					charging_bill.setPort_no(Integer.valueOf(portNo));
					charging_bill.setStart_time(now);
					charging_bill.setUser_pay_card(stateBody.getUserCard());
					//				bill.setOffline_balance_start(map.get("offline_balance_start"));
					charging_bill.setOffline_is_pay(OmsConstant.PayStatus.OfflineUnpaid);
					charging_bill.setStart_type(OmsConstant.ChargerStartupType.Immediately);
					String start_type = stateBody.getStartingType();
					charging_bill.setControl_type(start_type.substring(1));
					charging_bill.setCreate_time(now);
					charging_bill.setStatus(OmsConstant.ChargingBillStatus.Charging);
					charging_bill.setValid_flag(1);
					omsChargerChargeBillRecordDao.save(charging_bill);
				}
				break;
			case "04":                                             //停止充电（0x04）
				//
				log.debug("stop charging");
				ChargingStoppedStateBody stopCharingBody = MessageAnalysisHelper.analyse(data, ChargingStoppedStateBody.class);
				log.debug(stopCharingBody);

				String oms_msg_charge_jrnl = stopCharingBody.getStartChargingSerialNo();
				String stop_charging_reason = stopCharingBody.getStopReason();

				boolean validstats_stop = false;
				String whereClause = " where charger_id = '" + chargerId + "' ";
				if(!"0".equals(portNo))
					whereClause += " and port_no = " + portNo + " ";
				log.debug("whereClause = " + whereClause);
				String sql_update = "";
				if (OmsConstant.ChargerType.AC.equals(chargerType))
				{
					OmsChargerStateAlternate ac_port = stateAlternateDao.findOneExampleByCondition(new OmsChargerStateAlternate(), whereClause);
					log.debug(ac_port.getCharge_status());
					if (OmsConstant.ChargerPortStatus.Charging == ac_port.getCharge_status())
					{
//						stateAlternateDao.exec(MessageFormat.format("update oms_charger_state_alternate set online_status = 1 ,charge_status =  {0}  " + whereClause, OmsConstant.ChargerPortStatus.Available, chargerId, portNo));
//						validstats_stop = stateAlternateDao.exec(MessageFormat.format("update oms_charger_state_alternate set online_status = 1 ,charge_status =  {0}  " + whereClause, OmsConstant.ChargerPortStatus.Available));
//						validstats_stop = true;
						sql_update = "update oms_charger_state_alternate set online_status = 1 ,charge_status = "+ OmsConstant.ChargerPortStatus.Available + whereClause;
						boolean result = false;
						validstats_stop = stateDirectDao.exec(sql_update);
						log.info(result);
						validstats_stop = true;
					}
				}
				else if (OmsConstant.ChargerType.DC.equals(chargerType))
				{
					OmsChargerStateDirect dc_port = stateDirectDao.findOneExampleByCondition(new OmsChargerStateDirect(), whereClause);
					log.debug(dc_port.getCharge_status());
					if (OmsConstant.ChargerPortStatus.Charging == dc_port.getCharge_status())
					{
//						stateDirectDao.exec(MessageFormat.format("update oms_charger_state_direct       set online_status = 1 ,charge_status =  {0}  " + whereClause, OmsConstant.ChargerPortStatus.Available, chargerId, portNo));
//						validstats_stop = stateDirectDao.exec(MessageFormat.format("update oms_charger_state_direct       set online_status = 1 ,charge_status =  {0}  " + whereClause, OmsConstant.ChargerPortStatus.Available));
//						validstats_stop = true;
						sql_update = "update oms_charger_state_direct set online_status = 1 ,charge_status = "+ OmsConstant.ChargerPortStatus.Available + whereClause;
						log.debug(sql_update);
						boolean result = false;
						validstats_stop = stateDirectDao.exec(sql_update);
						log.info(result);
						validstats_stop = true;
					}
				}
				log.debug("update oms_charger_state result is  "+validstats_stop);

 				OmsChargerChargeBillRecord complete_bill = omsChargerChargeBillRecordDao.findOneExampleByCondition(new OmsChargerChargeBillRecord(), MessageFormat.format("WHERE msg_charge_jrnl = ''{0}'' and charger_id = ''{1}''", oms_msg_charge_jrnl, chargerId));
				log.debug(complete_bill);
				if(complete_bill == null || !validstats_stop)
				{
					reply_code = OmsConstant.MsgResponseCodeEnum.SysError.value();
				}
				else
				{
					complete_bill.setMsg_charge_end_jrnl(header.getChargerSerialNo());
					complete_bill.setEnd_time(now);
					complete_bill.setDuration(DateUtils.computeInterval(now, complete_bill.getStart_time()));
					complete_bill.setCharge_end_reason(stop_charging_reason);
					complete_bill.setStatus(OmsConstant.ChargingBillStatus.ChargingComplete);
					omsChargerChargeBillRecordDao.updateObject(complete_bill);
				}
				break;
			case "05":                                             //刷卡（0x05）d``````````````
				TapCardStateBody tapCardStateBody = MessageAnalysisHelper.analyse(data, TapCardStateBody.class);
				String cardNo = tapCardStateBody.getUserCard();

				// 1.根据卡的类型到主服务器获取卡状态和余额信息等
				int cardState = 0; // 主服务器返回(0:未激活, 1:激活, 2:冻结, 3:挂失, 4:注销)
				String returnBalance = "0.00"; // 当前卡号余额, BIN码, 4(放大100倍,低字节在前,高字节在后0x10 0x0e 0x00 0x00  表示充电金额为36元。精确:0.01元)
				String returnCardState = "00"; // 当前卡状态(0x00 正常, 0x01 用户卡号未激活, 0x02 用户卡号已被冻结, 0x03 用户卡号已挂失, 0x04 用户卡号已注销, 0x05 用户卡号不存在, 0x06 用户卡号类型错误, 0xFF 用户卡号已经欠费)
				if (CardUtils.generateCardType(cardNo).equals(OmsConstant.CardTypeEnum.Cash))
				{ // 06 现金卡
					MasterQueryOfflineCardVO.MasterQueryOfflineCardParamVO offlineCardParam = new MasterQueryOfflineCardVO.MasterQueryOfflineCardParamVO();
					offlineCardParam.setCardNo(cardNo);
					MasterQueryOfflineCardVO.MasterQueryOfflineCardRetVO result = mainServerClient.queryOfflineCard(offlineCardParam);
					if (result == null || result.getIsSuccess() != 1)
					{ // 0x05 卡号不存在
						cardState = 5;
						reply_code = OmsConstant.MsgResponseCodeEnum.SysError.value();
					}
					else
					{
						cardState = result.getCardState();
						returnBalance = result.getAcctBal();
						BigDecimal decimal = new BigDecimal(returnBalance);
						if (decimal.compareTo(BigDecimal.ZERO) == -1)
						{ // 0xFF 用户卡号已经欠费
							cardState = 7;
							returnBalance = decimal.multiply(new BigDecimal(-1)).toString();
						}
					}
				}
				else if (CardUtils.generateCardType(cardNo).equals(OmsConstant.CardTypeEnum.Identity))
				{ // 05 身份认证卡
					MasterQueryIdentityCardVO.MasterQueryIdentityCardParamVO identityCardParam = new MasterQueryIdentityCardVO.MasterQueryIdentityCardParamVO();
					identityCardParam.setCardNo(cardNo);
					MasterQueryIdentityCardVO.MasterQueryIdentityCardRetVO result = mainServerClient.queryIdentityCardByNo(identityCardParam);
					if (result == null || result.getIsSuccess() != 1)
					{ // 0x05 卡号不存在
						cardState = 5;
						reply_code = OmsConstant.MsgResponseCodeEnum.SysError.value();
					}
					else
					{
						cardState = result.getCardState();
					}
				}
				else
				{ // 0x06 用户卡号类型错误
					cardState = 6;
					reply_code = OmsConstant.MsgResponseCodeEnum.SysError.value();
				}

				switch (cardState)
				{ // 主服务器返回(0:未激活, 1:激活, 2:冻结, 3:挂失, 4:注销)
					case 0: // 0x01 用户卡号未激活
						returnCardState = "01";
						break;
					case 1:    // 0x00 正常
						returnCardState = "00";
						break;
					case 7:    // 0xFF 用户卡号已经欠费
						returnCardState = "FF";
						break;
					case 2:
					case 3:
					case 4:
					case 5:
					case 6:
						returnCardState = "0".concat(String.valueOf(cardState));
						break;
					default: // 0x00 正常
						returnCardState = "00";
						break;
				}

				// 2.根据卡的状态处理对应业务
				if (cardState == OmsConstant.CardStateEnum.Active)
				{ // 1.激活状态
					if (OmsConstant.ChargerType.AC.equals(chargerType))
					{
						stateAlternateDao.exec(MessageFormat
								.format("update oms_charger_state_alternate set online_status = 1, charge_status = {0} where charger_id = ''{1}'' and port_no = {2} ", OmsConstant.ChargerPortStatus.ReadingCard, chargerId,
										portNo));
					}
					else if (OmsConstant.ChargerType.DC.equals(chargerType))
					{
						stateDirectDao.exec(MessageFormat
								.format("update oms_charger_state_direct set online_status = 1, charge_status = {0} where charger_id = ''{1}'' and port_no = {2} ", OmsConstant.ChargerPortStatus.ReadingCard, chargerId,
										portNo));
					}
				}
				else
				{ // 其他状态,不能操作
					reply_code = OmsConstant.MsgResponseCodeEnum.UserCardNoAuth.value();
				}
				// 封装下发报文信息
				returnBalance = StringUtil.float10to16ByParamDesc(returnBalance, 100, 8);
				body = returnCardState + returnBalance;
				break;
			case "06":                                             //电桩故障（0x06）
				DownStateBody downStateBody = MessageAnalysisHelper.analyse(data, DownStateBody.class);
				String error_code = downStateBody.getDetail();
				if (OmsConstant.ChargerType.AC.equals(chargerType))
				{
					stateAlternateDao.exec(MessageFormat
							.format("update oms_charger_state_alternate set online_status = 1 ,charge_status =  {0} where charger_id = ''{1}'' and port_no = {2} ", OmsConstant.ChargerPortStatus.Down, chargerId, portNo));

				}
				else if (OmsConstant.ChargerType.DC.equals(chargerType))
				{
					stateDirectDao.exec(MessageFormat
							.format("update oms_charger_state_direct       set online_status = 1 ,charge_status =  {0} where charger_id = ''{1}'' and port_no = {2} ", OmsConstant.ChargerPortStatus.Down, chargerId,
									portNo));

				}


				OmsChargerErrorRecord omsChargerErrorRecord = new OmsChargerErrorRecord();
				omsChargerErrorRecord.setCharger_id(chargerId);
				omsChargerErrorRecord.setError_code(error_code);
				omsChargerErrorRecord.setError_msg(OmsConstant.MsgFaultCodeEnum.getMsgFaultCodeEnum(error_code).desc());
				omsChargerErrorRecord.setStatus(0);//未处理
				omsChargerErrorRecord.setValid_flag(1);
				omsChargerErrorRecord.setCreate_time(now);
				omsChargerErrorRecord.setCreate_oper_id("0000000000");//表示桩提交的
				omsChargerErrorRecordDao.save(omsChargerErrorRecord);
				break;
			case "07":                                             //停车位状态(0x07) 2.0暂时不做
				break;
			default:
				throw new BizException("invalid state " + stateChangeBody.getStateType());
		}

		String msg = messageWrapper.wrapReplyMsg(body, "B2", chargerId, chargerType, portNo.toString(), "00", reply_code, header.getChargerSerialNo());

		return msg;
	}

	@Override
	public Map<String, String> ev3c2uploadChargeData(Map<String, String> map)
	{
		//存入redis中
		String chargerId = map.get("chargerId");
		String portNo = map.get("portNo");
		Integer port_No = Integer.valueOf(portNo);
		String key = chargerId + map.get("oms_msg_charge_jrnl") + "_uploadChargeData";
		String key_charging = chargerId + String.format("%02d", port_No) + "_status";

		Jedis jedis = RedisClient.getConnect();
		String json = jedis.get(key_charging);
		ChargeDataUploadingVO vo = null;
		if(json == null)
		{
			vo = new ChargeDataUploadingVO();
		}
		else
		{
			vo = JSON.parseObject(json, ChargeDataUploadingVO.class);
		}
		vo.setOms_msg_charge_jrnl(map.get("oms_msg_charge_jrnl"));
		vo.setCharger_kwh(map.get("charger_kwh"));
		vo.setCharger_time(map.get("charger_time"));
		vo.setCharger_fee(map.get("charger_fee"));
		vo.setChar_bill(map.get("char_bill"));
		vo.setCharger_v(map.get("charger_v"));
		vo.setCharger_i(map.get("charger_i"));
		vo.setCharger_p(map.get("charger_p"));
		vo.setSoc(map.get("soc"));
		vo.setRemaining_time(map.get("remaining_time"));
		json = JSON.toJSONString(vo);

		StringBuffer temp = new StringBuffer();
		temp.append(map.get("oms_msg_charge_jrnl")).append(",");
		temp.append(map.get("charger_kwh")).append(",");
		temp.append(map.get("charger_time")).append(",");
		temp.append(map.get("charger_fee")).append(",");
		temp.append(map.get("char_bill")).append(",");
		temp.append(map.get("charger_v")).append(",");
		temp.append(map.get("charger_i")).append(",");
		temp.append(map.get("charger_p")).append(",");
		temp.append(map.get("soc")).append(",");
		temp.append(map.get("remaining_time"));

		jedis.rpush(key, temp.toString());
		jedis.set(key_charging, json);
		jedis.close();


		map.put("msgResponseCode", OmsConstant.MsgResponseCodeEnum.Normal.value());
		return map;
	}

}
